Renaming of GBP resources

The following resources are being renamed:

Endpoints to Policy Targets
Endpoints Group to Policy Target Groups
Contracts to Policy Rule Sets

The changes to the spec are outlined in:
https://review.openstack.org/#/c/134747

This cascades to a number of changes including DB.

Change-Id: I5139a59fec135d39a32838ce1d05e168a55e2fec
Partially-implements: blueprint group-based-policy-abstraction
This commit is contained in:
Sumit Naiksatam 2014-11-12 05:05:52 -08:00
parent b3be657650
commit 0322515b48
37 changed files with 2573 additions and 2426 deletions

View File

@ -25,3 +25,12 @@ GBP project management (blueprints, bugs) is done via Launchpad:
For help using or hacking on GBP, you can send mail to For help using or hacking on GBP, you can send mail to
<mailto:openstack-dev@lists.openstack.org>. <mailto:openstack-dev@lists.openstack.org>.
Acronyms used in code for brevity:
PT: Policy Target
PTG: Policy Target Group
PR: Policy Rule
PRS: Policy Rule Set
L2P: L2 Policy
L3P: L3 Policy
NSP: Network Service Policy

View File

@ -32,12 +32,9 @@ MAX_IPV4_SUBNET_PREFIX_LENGTH = 31
MAX_IPV6_SUBNET_PREFIX_LENGTH = 127 MAX_IPV6_SUBNET_PREFIX_LENGTH = 127
class Endpoint(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): class PolicyTarget(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):
"""Endpoint is the lowest unit of abstraction on which a policy is applied. """Lowest unit of abstraction on which a policy is applied."""
__tablename__ = 'gp_policy_targets'
This Endpoint is unrelated to the Endpoint terminology used in Keystone.
"""
__tablename__ = 'gp_endpoints'
type = sa.Column(sa.String(15)) type = sa.Column(sa.String(15))
__mapper_args__ = { __mapper_args__ = {
'polymorphic_on': type, 'polymorphic_on': type,
@ -45,36 +42,40 @@ class Endpoint(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):
} }
name = sa.Column(sa.String(50)) name = sa.Column(sa.String(50))
description = sa.Column(sa.String(255)) description = sa.Column(sa.String(255))
endpoint_group_id = sa.Column(sa.String(36), policy_target_group_id = sa.Column(sa.String(36),
sa.ForeignKey('gp_endpoint_groups.id'), sa.ForeignKey(
nullable=True) 'gp_policy_target_groups.id'),
nullable=True)
class EndpointGroupContractProvidingAssociation(model_base.BASEV2): class PTGToPRSProvidingAssociation(model_base.BASEV2):
"""Models many to many providing relation between EPGs and Contracts.""" """Many to many providing relation between PTGs and Policy Rule Sets."""
__tablename__ = 'gp_endpoint_group_contract_providing_associations' __tablename__ = 'gp_ptg_to_prs_providing_associations'
contract_id = sa.Column(sa.String(36), policy_rule_set_id = sa.Column(sa.String(36),
sa.ForeignKey('gp_contracts.id'), sa.ForeignKey('gp_policy_rule_sets.id'),
primary_key=True) primary_key=True)
endpoint_group_id = sa.Column(sa.String(36), policy_target_group_id = sa.Column(sa.String(36),
sa.ForeignKey('gp_endpoint_groups.id'), sa.ForeignKey(
primary_key=True) 'gp_policy_target_groups.id'),
primary_key=True)
class EndpointGroupContractConsumingAssociation(model_base.BASEV2): class PTGToPRSConsumingAssociation(model_base.BASEV2):
"""Models many to many consuming relation between EPGs and Contracts.""" """Many to many consuming relation between PTGs and Policy Rule Sets."""
__tablename__ = 'gp_endpoint_group_contract_consuming_associations' __tablename__ = 'gp_ptg_to_prs_consuming_associations'
contract_id = sa.Column(sa.String(36), policy_rule_set_id = sa.Column(sa.String(36),
sa.ForeignKey('gp_contracts.id'), sa.ForeignKey('gp_policy_rule_sets.id'),
primary_key=True) primary_key=True)
endpoint_group_id = sa.Column(sa.String(36), policy_target_group_id = sa.Column(sa.String(36),
sa.ForeignKey('gp_endpoint_groups.id'), sa.ForeignKey(
primary_key=True) 'gp_policy_target_groups.id'),
primary_key=True)
class EndpointGroup(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): class PolicyTargetGroup(model_base.BASEV2, models_v2.HasId,
"""Represents an Endpoint Group that is a collection of endpoints.""" models_v2.HasTenant):
__tablename__ = 'gp_endpoint_groups' """It is a collection of policy_targets."""
__tablename__ = 'gp_policy_target_groups'
type = sa.Column(sa.String(15)) type = sa.Column(sa.String(15))
__mapper_args__ = { __mapper_args__ = {
'polymorphic_on': type, 'polymorphic_on': type,
@ -82,23 +83,24 @@ class EndpointGroup(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):
} }
name = sa.Column(sa.String(50)) name = sa.Column(sa.String(50))
description = sa.Column(sa.String(255)) description = sa.Column(sa.String(255))
endpoints = orm.relationship(Endpoint, backref='endpoint_group') policy_targets = orm.relationship(PolicyTarget,
backref='policy_target_group')
l2_policy_id = sa.Column(sa.String(36), l2_policy_id = sa.Column(sa.String(36),
sa.ForeignKey('gp_l2_policies.id'), sa.ForeignKey('gp_l2_policies.id'),
nullable=True) nullable=True)
network_service_policy_id = sa.Column( network_service_policy_id = sa.Column(
sa.String(36), sa.ForeignKey('gp_network_service_policies.id'), sa.String(36), sa.ForeignKey('gp_network_service_policies.id'),
nullable=True) nullable=True)
provided_contracts = orm.relationship( provided_policy_rule_sets = orm.relationship(
EndpointGroupContractProvidingAssociation, PTGToPRSProvidingAssociation,
backref='providing_endpoint_group', cascade='all, delete-orphan') backref='providing_policy_target_group', cascade='all, delete-orphan')
consumed_contracts = orm.relationship( consumed_policy_rule_sets = orm.relationship(
EndpointGroupContractConsumingAssociation, PTGToPRSConsumingAssociation,
backref='consuming_endpoint_group', cascade='all, delete-orphan') backref='consuming_policy_target_group', cascade='all, delete-orphan')
class L2Policy(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): class L2Policy(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):
"""Represents a L2 Policy for a collection of endpoint_groups.""" """Represents a L2 Policy for a collection of policy_target_groups."""
__tablename__ = 'gp_l2_policies' __tablename__ = 'gp_l2_policies'
type = sa.Column(sa.String(15)) type = sa.Column(sa.String(15))
__mapper_args__ = { __mapper_args__ = {
@ -107,7 +109,8 @@ class L2Policy(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):
} }
name = sa.Column(sa.String(50)) name = sa.Column(sa.String(50))
description = sa.Column(sa.String(255)) description = sa.Column(sa.String(255))
endpoint_groups = orm.relationship(EndpointGroup, backref='l2_policy') policy_target_groups = orm.relationship(PolicyTargetGroup,
backref='l2_policy')
l3_policy_id = sa.Column(sa.String(36), l3_policy_id = sa.Column(sa.String(36),
sa.ForeignKey('gp_l3_policies.id'), sa.ForeignKey('gp_l3_policies.id'),
nullable=True) nullable=True)
@ -146,18 +149,18 @@ class NetworkServicePolicy(
__tablename__ = 'gp_network_service_policies' __tablename__ = 'gp_network_service_policies'
name = sa.Column(sa.String(50)) name = sa.Column(sa.String(50))
description = sa.Column(sa.String(255)) description = sa.Column(sa.String(255))
endpoint_groups = orm.relationship(EndpointGroup, policy_target_groups = orm.relationship(PolicyTargetGroup,
backref='network_service_policy') backref='network_service_policy')
network_service_params = orm.relationship(NetworkServiceParam, network_service_params = orm.relationship(
backref='network_service_policy') NetworkServiceParam, backref='network_service_policy')
class ContractPolicyRuleAssociation(model_base.BASEV2): class PRSToPRAssociation(model_base.BASEV2):
"""Models the many to many relation between Contract and Policy rules.""" """Many to many relation between Policy Rule Set and Policy rules."""
__tablename__ = 'gp_contract_policy_rule_associations' __tablename__ = 'gp_prs_to_pr_associations'
contract_id = sa.Column(sa.String(36), policy_rule_set_id = sa.Column(sa.String(36),
sa.ForeignKey('gp_contracts.id'), sa.ForeignKey('gp_policy_rule_sets.id'),
primary_key=True) primary_key=True)
policy_rule_id = sa.Column(sa.String(36), policy_rule_id = sa.Column(sa.String(36),
sa.ForeignKey('gp_policy_rules.id'), sa.ForeignKey('gp_policy_rules.id'),
primary_key=True) primary_key=True)
@ -225,27 +228,27 @@ class PolicyAction(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):
cascade='all', backref='gp_policy_actions') cascade='all', backref='gp_policy_actions')
class Contract(model_base.BASEV2, models_v2.HasTenant): class PolicyRuleSet(model_base.BASEV2, models_v2.HasTenant):
"""Represents a Contract that is a collection of Policy rules.""" """It is a collection of Policy rules."""
__tablename__ = 'gp_contracts' __tablename__ = 'gp_policy_rule_sets'
id = sa.Column(sa.String(36), primary_key=True, id = sa.Column(sa.String(36), primary_key=True,
default=uuidutils.generate_uuid) default=uuidutils.generate_uuid)
name = sa.Column(sa.String(50)) name = sa.Column(sa.String(50))
description = sa.Column(sa.String(255)) description = sa.Column(sa.String(255))
parent_id = sa.Column(sa.String(255), sa.ForeignKey('gp_contracts.id'), parent_id = sa.Column(sa.String(255),
sa.ForeignKey('gp_policy_rule_sets.id'),
nullable=True) nullable=True)
child_contracts = orm.relationship('Contract', child_policy_rule_sets = orm.relationship(
backref=orm.backref('parent', 'PolicyRuleSet', backref=orm.backref('parent', remote_side=[id]))
remote_side=[id])) policy_rules = orm.relationship(PRSToPRAssociation,
policy_rules = orm.relationship(ContractPolicyRuleAssociation, backref='policy_rule_set', lazy="joined",
backref='contract', lazy="joined",
cascade='all, delete-orphan') cascade='all, delete-orphan')
providing_endpoint_groups = orm.relationship( providing_policy_target_groups = orm.relationship(
EndpointGroupContractProvidingAssociation, backref='provided_contract', PTGToPRSProvidingAssociation,
lazy="joined", cascade='all') backref='provided_policy_rule_set', lazy="joined", cascade='all')
consuming_endpoint_groups = orm.relationship( consuming_policy_target_groups = orm.relationship(
EndpointGroupContractConsumingAssociation, backref='consumed_contract', PTGToPRSConsumingAssociation,
lazy="joined", cascade='all') backref='consumed_policy_rule_set', lazy="joined", cascade='all')
class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase, class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
@ -260,18 +263,20 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(GroupPolicyDbPlugin, self).__init__(*args, **kwargs) super(GroupPolicyDbPlugin, self).__init__(*args, **kwargs)
def _get_endpoint(self, context, endpoint_id): def _get_policy_target(self, context, policy_target_id):
try: try:
return self._get_by_id(context, Endpoint, endpoint_id) return self._get_by_id(context, PolicyTarget, policy_target_id)
except exc.NoResultFound: except exc.NoResultFound:
raise gpolicy.EndpointNotFound(endpoint_id=endpoint_id) raise gpolicy.PolicyTargetNotFound(
policy_target_id=policy_target_id)
def _get_endpoint_group(self, context, endpoint_group_id): def _get_policy_target_group(self, context, policy_target_group_id):
try: try:
return self._get_by_id(context, EndpointGroup, endpoint_group_id) return self._get_by_id(
context, PolicyTargetGroup, policy_target_group_id)
except exc.NoResultFound: except exc.NoResultFound:
raise gpolicy.EndpointGroupNotFound( raise gpolicy.PolicyTargetGroupNotFound(
endpoint_group_id=endpoint_group_id) policy_target_group_id=policy_target_group_id)
def _get_l2_policy(self, context, l2_policy_id): def _get_l2_policy(self, context, l2_policy_id):
try: try:
@ -283,8 +288,7 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
try: try:
return self._get_by_id(context, L3Policy, l3_policy_id) return self._get_by_id(context, L3Policy, l3_policy_id)
except exc.NoResultFound: except exc.NoResultFound:
raise gpolicy.L3PolicyNotFound(l3_policy_id= raise gpolicy.L3PolicyNotFound(l3_policy_id=l3_policy_id)
l3_policy_id)
def _get_network_service_policy(self, context, network_service_policy_id): def _get_network_service_policy(self, context, network_service_policy_id):
try: try:
@ -299,16 +303,16 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
return self._get_by_id(context, PolicyClassifier, return self._get_by_id(context, PolicyClassifier,
policy_classifier_id) policy_classifier_id)
except exc.NoResultFound: except exc.NoResultFound:
raise gpolicy.PolicyClassifierNotFound(policy_classifier_id= raise gpolicy.PolicyClassifierNotFound(
policy_classifier_id) policy_classifier_id=policy_classifier_id)
def _get_policy_action(self, context, policy_action_id): def _get_policy_action(self, context, policy_action_id):
try: try:
policy_action = self._get_by_id(context, PolicyAction, policy_action = self._get_by_id(context, PolicyAction,
policy_action_id) policy_action_id)
except exc.NoResultFound: except exc.NoResultFound:
raise gpolicy.PolicyActionNotFound(policy_action_id= raise gpolicy.PolicyActionNotFound(
policy_action_id) policy_action_id=policy_action_id)
return policy_action return policy_action
def _get_policy_rule(self, context, policy_rule_id): def _get_policy_rule(self, context, policy_rule_id):
@ -316,16 +320,18 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
policy_rule = self._get_by_id(context, PolicyRule, policy_rule = self._get_by_id(context, PolicyRule,
policy_rule_id) policy_rule_id)
except exc.NoResultFound: except exc.NoResultFound:
raise gpolicy.PolicyRuleNotFound(policy_rule_id= raise gpolicy.PolicyRuleNotFound(
policy_rule_id) policy_rule_id=policy_rule_id)
return policy_rule return policy_rule
def _get_contract(self, context, contract_id): def _get_policy_rule_set(self, context, policy_rule_set_id):
try: try:
contract = self._get_by_id(context, Contract, contract_id) policy_rule_set = self._get_by_id(
context, PolicyRuleSet, policy_rule_set_id)
except exc.NoResultFound: except exc.NoResultFound:
raise gpolicy.ContractNotFound(contract_id=contract_id) raise gpolicy.PolicyRuleSetNotFound(
return contract policy_rule_set_id=policy_rule_set_id)
return policy_rule_set
@staticmethod @staticmethod
def _get_min_max_ports_from_range(port_range): def _get_min_max_ports_from_range(port_range):
@ -359,8 +365,8 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
if action_id not in actions_set: if action_id not in actions_set:
# If we find an invalid action in the list we # If we find an invalid action in the list we
# do not perform the update # do not perform the update
raise gpolicy.PolicyActionNotFound(policy_action_id= raise gpolicy.PolicyActionNotFound(
action_id) policy_action_id=action_id)
# New list of actions is valid so we will first reset the existing # New list of actions is valid so we will first reset the existing
# list and then add each action in order. # list and then add each action in order.
# Note that the list could be empty in which case we interpret # Note that the list could be empty in which case we interpret
@ -371,87 +377,93 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
policy_action_id=action_id) policy_action_id=action_id)
pr_db.policy_actions.append(assoc) pr_db.policy_actions.append(assoc)
def _validate_contract_list(self, context, contracts_id_list): def _validate_policy_rule_set_list(self, context,
policy_rule_sets_id_list):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
filters = {'id': [c_id for c_id in contracts_id_list]} filters = {'id': [c_id for c_id in policy_rule_sets_id_list]}
contracts_in_db = self._get_collection_query( policy_rule_sets_in_db = self._get_collection_query(
context, Contract, filters=filters) context, PolicyRuleSet, filters=filters)
existing_contract_ids = set(c_db['id'] for c_db in contracts_in_db) existing_policy_rule_set_ids = set(
for contract_id in contracts_id_list: c_db['id'] for c_db in policy_rule_sets_in_db)
if contract_id not in existing_contract_ids: for policy_rule_set_id in policy_rule_sets_id_list:
# If we find an invalid contract id in the list we if policy_rule_set_id not in existing_policy_rule_set_ids:
# If we find an invalid policy_rule_set id in the list we
# dont process the entire list # dont process the entire list
raise gpolicy.ContractNotFound(contract_id=contract_id) raise gpolicy.PolicyRuleSetNotFound(
return contracts_in_db policy_rule_set_id=policy_rule_set_id)
return policy_rule_sets_in_db
def _set_providers_or_consumers_for_endpoint_group(self, context, epg_db, def _set_providers_or_consumers_for_policy_target_group(
contracts_dict, self, context, ptg_db, policy_rule_sets_dict, provider=True):
provider=True): # TODO(Sumit): Check that the same policy_rule_set ID does not belong
# TODO(Sumit): Check that the same contract ID does not belong to # to provider and consumer dicts
# provider and consumer dicts if not policy_rule_sets_dict:
if not contracts_dict:
if provider: if provider:
epg_db.provided_contracts = [] ptg_db.provided_policy_rule_sets = []
return return
else: else:
epg_db.consumed_contracts = [] ptg_db.consumed_policy_rule_sets = []
return return
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
contracts_id_list = contracts_dict.keys() policy_rule_sets_id_list = policy_rule_sets_dict.keys()
# We will first check if the new list of contracts is valid # We will first check if the new list of policy_rule_sets is valid
self._validate_contract_list(context, contracts_id_list) self._validate_policy_rule_set_list(
# New list of contracts is valid so we will first reset the context, policy_rule_sets_id_list)
# existing list and then add each contract. # New list of policy_rule_sets is valid so we will first reset the
# existing list and then add each policy_rule_set.
# Note that the list could be empty in which case we interpret # Note that the list could be empty in which case we interpret
# it as clearing existing rules. # it as clearing existing rules.
if provider: if provider:
epg_db.provided_contracts = [] ptg_db.provided_policy_rule_sets = []
else: else:
epg_db.consumed_contracts = [] ptg_db.consumed_policy_rule_sets = []
for contract_id in contracts_id_list: for policy_rule_set_id in policy_rule_sets_id_list:
if provider: if provider:
assoc = EndpointGroupContractProvidingAssociation( assoc = PTGToPRSProvidingAssociation(
endpoint_group_id=epg_db.id, policy_target_group_id=ptg_db.id,
contract_id=contract_id) policy_rule_set_id=policy_rule_set_id)
epg_db.provided_contracts.append(assoc) ptg_db.provided_policy_rule_sets.append(assoc)
else: else:
assoc = EndpointGroupContractConsumingAssociation( assoc = PTGToPRSConsumingAssociation(
endpoint_group_id=epg_db.id, policy_target_group_id=ptg_db.id,
contract_id=contract_id) policy_rule_set_id=policy_rule_set_id)
epg_db.consumed_contracts.append(assoc) ptg_db.consumed_policy_rule_sets.append(assoc)
def _set_children_for_contract(self, context, contract_db, child_id_list): def _set_children_for_policy_rule_set(self, context,
policy_rule_set_db, child_id_list):
if not child_id_list: if not child_id_list:
contract_db.child_contracts = [] policy_rule_set_db.child_policy_rule_sets = []
return return
if contract_db['parent_id']: if policy_rule_set_db['parent_id']:
# Only one hierarchy level allowed for now # Only one hierarchy level allowed for now
raise gpolicy.ThreeLevelContractHierarchyNotSupported( raise gpolicy.ThreeLevelPolicyRuleSetHierarchyNotSupported(
contract_id=contract_db['id']) policy_rule_set_id=policy_rule_set_db['id'])
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
# We will first check if the new list of contracts is valid # We will first check if the new list of policy_rule_sets is valid
contracts_in_db = self._validate_contract_list( policy_rule_sets_in_db = self._validate_policy_rule_set_list(
context, child_id_list) context, child_id_list)
for child in contracts_in_db: for child in policy_rule_sets_in_db:
if (child['child_contracts'] or if (child['child_policy_rule_sets'] or
child['id'] == contract_db['id']): child['id'] == policy_rule_set_db['id']):
# Only one level contract relationship supported for now # Only one level policy_rule_set relationship supported for
# No loops allowed # now. No loops allowed
raise gpolicy.BadContractRelationship( raise gpolicy.BadPolicyRuleSetRelationship(
parent_id=contract_db['id'], child_id=child['id']) parent_id=policy_rule_set_db['id'],
# New list of child contracts is valid so we will first reset the child_id=child['id'])
# existing list and then add each contract. # New list of child policy_rule_sets is valid so we will first
# reset the existing list and then add each policy_rule_set.
# Note that the list could be empty in which case we interpret # Note that the list could be empty in which case we interpret
# it as clearing existing child contracts. # it as clearing existing child policy_rule_sets.
contract_db.child_contracts = [] policy_rule_set_db.child_policy_rule_sets = []
for child in contracts_in_db: for child in policy_rule_sets_in_db:
contract_db.child_contracts.append(child) policy_rule_set_db.child_policy_rule_sets.append(child)
def _set_rules_for_contract(self, context, contract_db, rule_id_list): def _set_rules_for_policy_rule_set(self, context,
ct_db = contract_db policy_rule_set_db, rule_id_list):
prs_db = policy_rule_set_db
if not rule_id_list: if not rule_id_list:
ct_db.policy_rules = [] prs_db.policy_rules = []
return return
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
# We will first check if the new list of rules is valid # We will first check if the new list of rules is valid
@ -468,42 +480,42 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
# list and then add each rule in order. # list and then add each rule in order.
# Note that the list could be empty in which case we interpret # Note that the list could be empty in which case we interpret
# it as clearing existing rules. # it as clearing existing rules.
ct_db.policy_rules = [] prs_db.policy_rules = []
for rule_id in rule_id_list: for rule_id in rule_id_list:
ct_rule_db = ContractPolicyRuleAssociation( prs_rule_db = PRSToPRAssociation(
policy_rule_id=rule_id, policy_rule_id=rule_id,
contract_id=ct_db.id) policy_rule_set_id=prs_db.id)
ct_db.policy_rules.append(ct_rule_db) prs_db.policy_rules.append(prs_rule_db)
def _process_contracts_for_epg(self, context, epg_db, epg): def _process_policy_rule_sets_for_ptg(self, context, ptg_db, ptg):
if 'provided_contracts' in epg: if 'provided_policy_rule_sets' in ptg:
self._set_providers_or_consumers_for_endpoint_group( self._set_providers_or_consumers_for_policy_target_group(
context, epg_db, epg['provided_contracts']) context, ptg_db, ptg['provided_policy_rule_sets'])
del epg['provided_contracts'] del ptg['provided_policy_rule_sets']
if 'consumed_contracts' in epg: if 'consumed_policy_rule_sets' in ptg:
self._set_providers_or_consumers_for_endpoint_group( self._set_providers_or_consumers_for_policy_target_group(
context, epg_db, epg['consumed_contracts'], False) context, ptg_db, ptg['consumed_policy_rule_sets'], False)
del epg['consumed_contracts'] del ptg['consumed_policy_rule_sets']
return epg return ptg
def _set_l3_policy_for_l2_policy(self, context, l2p_id, l3p_id): def _set_l3_policy_for_l2_policy(self, context, l2p_id, l3p_id):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
l2p_db = self._get_l2_policy(context, l2p_id) l2p_db = self._get_l2_policy(context, l2p_id)
l2p_db.l3_policy_id = l3p_id l2p_db.l3_policy_id = l3p_id
def _set_l2_policy_for_endpoint_group(self, context, epg_id, l2p_id): def _set_l2_policy_for_policy_target_group(self, context, ptg_id, l2p_id):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
epg_db = self._get_endpoint_group(context, epg_id) ptg_db = self._get_policy_target_group(context, ptg_id)
epg_db.l2_policy_id = l2p_id ptg_db.l2_policy_id = l2p_id
def _set_network_service_policy_for_endpoint_group( def _set_network_service_policy_for_policy_target_group(
self, context, epg_id, nsp_id): self, context, ptg_id, nsp_id):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
epg_db = self._get_endpoint_group(context, epg_id) ptg_db = self._get_policy_target_group(context, ptg_id)
epg_db.network_service_policy_id = nsp_id ptg_db.network_service_policy_id = nsp_id
def _set_params_for_network_service_policy( def _set_params_for_network_service_policy(
self, context, network_service_policy_db, network_service_policy): self, context, network_service_policy_db, network_service_policy):
nsp_db = network_service_policy_db nsp_db = network_service_policy_db
params = network_service_policy['network_service_params'] params = network_service_policy['network_service_params']
if not params: if not params:
@ -519,27 +531,29 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
nsp_db.network_service_params.append(param_db) nsp_db.network_service_params.append(param_db)
del network_service_policy['network_service_params'] del network_service_policy['network_service_params']
def _make_endpoint_dict(self, ep, fields=None): def _make_policy_target_dict(self, pt, fields=None):
res = {'id': ep['id'], res = {'id': pt['id'],
'tenant_id': ep['tenant_id'], 'tenant_id': pt['tenant_id'],
'name': ep['name'], 'name': pt['name'],
'description': ep['description'], 'description': pt['description'],
'endpoint_group_id': ep['endpoint_group_id']} 'policy_target_group_id': pt['policy_target_group_id']}
return self._fields(res, fields) return self._fields(res, fields)
def _make_endpoint_group_dict(self, epg, fields=None): def _make_policy_target_group_dict(self, ptg, fields=None):
res = {'id': epg['id'], res = {'id': ptg['id'],
'tenant_id': epg['tenant_id'], 'tenant_id': ptg['tenant_id'],
'name': epg['name'], 'name': ptg['name'],
'description': epg['description'], 'description': ptg['description'],
'l2_policy_id': epg['l2_policy_id'], 'l2_policy_id': ptg['l2_policy_id'],
'network_service_policy_id': epg['network_service_policy_id']} 'network_service_policy_id': ptg['network_service_policy_id']}
res['endpoints'] = [ep['id'] res['policy_targets'] = [
for ep in epg['endpoints']] pt['id'] for pt in ptg['policy_targets']]
res['provided_contracts'] = [pc['contract_id'] res['provided_policy_rule_sets'] = (
for pc in epg['provided_contracts']] [pprs['policy_rule_set_id'] for pprs in ptg[
res['consumed_contracts'] = [cc['contract_id'] 'provided_policy_rule_sets']])
for cc in epg['consumed_contracts']] res['consumed_policy_rule_sets'] = (
[cprs['policy_rule_set_id'] for cprs in ptg[
'consumed_policy_rule_sets']])
return self._fields(res, fields) return self._fields(res, fields)
def _make_l2_policy_dict(self, l2p, fields=None): def _make_l2_policy_dict(self, l2p, fields=None):
@ -548,8 +562,8 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
'name': l2p['name'], 'name': l2p['name'],
'description': l2p['description'], 'description': l2p['description'],
'l3_policy_id': l2p['l3_policy_id']} 'l3_policy_id': l2p['l3_policy_id']}
res['endpoint_groups'] = [epg['id'] res['policy_target_groups'] = [
for epg in l2p['endpoint_groups']] ptg['id'] for ptg in l2p['policy_target_groups']]
return self._fields(res, fields) return self._fields(res, fields)
def _make_l3_policy_dict(self, l3p, fields=None): def _make_l3_policy_dict(self, l3p, fields=None):
@ -570,8 +584,8 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
'tenant_id': nsp['tenant_id'], 'tenant_id': nsp['tenant_id'],
'name': nsp['name'], 'name': nsp['name'],
'description': nsp['description']} 'description': nsp['description']}
res['endpoint_groups'] = [epg['id'] res['policy_target_groups'] = [
for epg in nsp['endpoint_groups']] ptg['id'] for ptg in nsp['policy_target_groups']]
params = [] params = []
for param in nsp['network_service_params']: for param in nsp['network_service_params']:
params.append({ params.append({
@ -614,36 +628,36 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
for pa in pr['policy_actions']] for pa in pr['policy_actions']]
return self._fields(res, fields) return self._fields(res, fields)
def _make_contract_dict(self, ct, fields=None): def _make_policy_rule_set_dict(self, prs, fields=None):
res = {'id': ct['id'], res = {'id': prs['id'],
'tenant_id': ct['tenant_id'], 'tenant_id': prs['tenant_id'],
'name': ct['name'], 'name': prs['name'],
'description': ct['description']} 'description': prs['description']}
if ct['parent']: if prs['parent']:
res['parent_id'] = ct['parent']['id'] res['parent_id'] = prs['parent']['id']
else: else:
res['parent_id'] = None res['parent_id'] = None
ctx = context.get_admin_context() ctx = context.get_admin_context()
if 'child_contracts' in ct: if 'child_policy_rule_sets' in prs:
# They have been updated # They have been updated
res['child_contracts'] = [child_ct['id'] res['child_policy_rule_sets'] = [
for child_ct in ct['child_contracts']] child_prs['id'] for child_prs in prs['child_policy_rule_sets']]
else: else:
with ctx.session.begin(subtransactions=True): with ctx.session.begin(subtransactions=True):
filters = {'parent_id': [ct['id']]} filters = {'parent_id': [prs['id']]}
child_contracts_in_db = self._get_collection_query( child_prs_in_db = self._get_collection_query(
ctx, Contract, filters=filters) ctx, PolicyRuleSet, filters=filters)
res['child_contracts'] = [child_ct['id'] res['child_policy_rule_sets'] = [child_prs['id']
for child_ct in for child_prs
child_contracts_in_db] in child_prs_in_db]
res['policy_rules'] = [pr['policy_rule_id'] res['policy_rules'] = [pr['policy_rule_id']
for pr in ct['policy_rules']] for pr in prs['policy_rules']]
return self._fields(res, fields) return self._fields(res, fields)
def _get_policy_rule_contracts(self, context, policy_rule_id): def _get_policy_rule_policy_rule_sets(self, context, policy_rule_id):
return [x['contract_id'] for x in return [x['policy_rule_set_id'] for x in
context.session.query(ContractPolicyRuleAssociation).filter_by( context.session.query(PRSToPRAssociation).filter_by(
policy_rule_id=policy_rule_id)] policy_rule_id=policy_rule_id)]
@staticmethod @staticmethod
@ -659,108 +673,108 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
# than size of the ip_pool's subnet # than size of the ip_pool's subnet
@log.log @log.log
def create_endpoint(self, context, endpoint): def create_policy_target(self, context, policy_target):
ep = endpoint['endpoint'] pt = policy_target['policy_target']
tenant_id = self._get_tenant_id_for_create(context, ep) tenant_id = self._get_tenant_id_for_create(context, pt)
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
ep_db = Endpoint(id=uuidutils.generate_uuid(), pt_db = PolicyTarget(
tenant_id=tenant_id, id=uuidutils.generate_uuid(), tenant_id=tenant_id,
name=ep['name'], name=pt['name'], description=pt['description'],
description=ep['description'], policy_target_group_id=pt['policy_target_group_id'])
endpoint_group_id=ep['endpoint_group_id']) context.session.add(pt_db)
context.session.add(ep_db) return self._make_policy_target_dict(pt_db)
return self._make_endpoint_dict(ep_db)
@log.log @log.log
def update_endpoint(self, context, endpoint_id, endpoint): def update_policy_target(self, context, policy_target_id, policy_target):
ep = endpoint['endpoint'] pt = policy_target['policy_target']
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
ep_db = self._get_endpoint(context, endpoint_id) pt_db = self._get_policy_target(context, policy_target_id)
ep_db.update(ep) pt_db.update(pt)
return self._make_endpoint_dict(ep_db) return self._make_policy_target_dict(pt_db)
@log.log @log.log
def delete_endpoint(self, context, endpoint_id): def delete_policy_target(self, context, policy_target_id):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
ep_db = self._get_endpoint(context, endpoint_id) pt_db = self._get_policy_target(context, policy_target_id)
context.session.delete(ep_db) context.session.delete(pt_db)
@log.log @log.log
def get_endpoint(self, context, endpoint_id, fields=None): def get_policy_target(self, context, policy_target_id, fields=None):
ep = self._get_endpoint(context, endpoint_id) pt = self._get_policy_target(context, policy_target_id)
return self._make_endpoint_dict(ep, fields) return self._make_policy_target_dict(pt, fields)
@log.log @log.log
def get_endpoints(self, context, filters=None, fields=None, def get_policy_targets(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None, sorts=None, limit=None, marker=None,
page_reverse=False): page_reverse=False):
marker_obj = self._get_marker_obj(context, 'endpoint', limit, marker_obj = self._get_marker_obj(context, 'policy_target', limit,
marker) marker)
return self._get_collection(context, Endpoint, return self._get_collection(context, PolicyTarget,
self._make_endpoint_dict, self._make_policy_target_dict,
filters=filters, fields=fields, filters=filters, fields=fields,
sorts=sorts, limit=limit, sorts=sorts, limit=limit,
marker_obj=marker_obj, marker_obj=marker_obj,
page_reverse=page_reverse) page_reverse=page_reverse)
@log.log @log.log
def get_endpoints_count(self, context, filters=None): def get_policy_targets_count(self, context, filters=None):
return self._get_collection_count(context, Endpoint, return self._get_collection_count(context, PolicyTarget,
filters=filters) filters=filters)
@log.log @log.log
def create_endpoint_group(self, context, endpoint_group): def create_policy_target_group(self, context, policy_target_group):
epg = endpoint_group['endpoint_group'] ptg = policy_target_group['policy_target_group']
tenant_id = self._get_tenant_id_for_create(context, epg) tenant_id = self._get_tenant_id_for_create(context, ptg)
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
epg_db = EndpointGroup(id=uuidutils.generate_uuid(), ptg_db = PolicyTargetGroup(
tenant_id=tenant_id, id=uuidutils.generate_uuid(), tenant_id=tenant_id,
name=epg['name'], name=ptg['name'], description=ptg['description'],
description=epg['description'], l2_policy_id=ptg['l2_policy_id'],
l2_policy_id=epg['l2_policy_id'], network_service_policy_id=ptg['network_service_policy_id'])
network_service_policy_id= context.session.add(ptg_db)
epg['network_service_policy_id']) self._process_policy_rule_sets_for_ptg(context, ptg_db, ptg)
context.session.add(epg_db) return self._make_policy_target_group_dict(ptg_db)
self._process_contracts_for_epg(context, epg_db, epg)
return self._make_endpoint_group_dict(epg_db)
@log.log @log.log
def update_endpoint_group(self, context, endpoint_group_id, def update_policy_target_group(self, context, policy_target_group_id,
endpoint_group): policy_target_group):
epg = endpoint_group['endpoint_group'] ptg = policy_target_group['policy_target_group']
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
epg_db = self._get_endpoint_group(context, endpoint_group_id) ptg_db = self._get_policy_target_group(
epg = self._process_contracts_for_epg(context, epg_db, epg) context, policy_target_group_id)
epg_db.update(epg) ptg = self._process_policy_rule_sets_for_ptg(context, ptg_db, ptg)
return self._make_endpoint_group_dict(epg_db) ptg_db.update(ptg)
return self._make_policy_target_group_dict(ptg_db)
@log.log @log.log
def delete_endpoint_group(self, context, endpoint_group_id): def delete_policy_target_group(self, context, policy_target_group_id):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
epg_db = self._get_endpoint_group(context, endpoint_group_id) ptg_db = self._get_policy_target_group(
context.session.delete(epg_db) context, policy_target_group_id)
context.session.delete(ptg_db)
@log.log @log.log
def get_endpoint_group(self, context, endpoint_group_id, fields=None): def get_policy_target_group(self, context, policy_target_group_id,
epg = self._get_endpoint_group(context, endpoint_group_id) fields=None):
return self._make_endpoint_group_dict(epg, fields) ptg = self._get_policy_target_group(context, policy_target_group_id)
return self._make_policy_target_group_dict(ptg, fields)
@log.log @log.log
def get_endpoint_groups(self, context, filters=None, fields=None, def get_policy_target_groups(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None, sorts=None, limit=None, marker=None,
page_reverse=False): page_reverse=False):
marker_obj = self._get_marker_obj(context, 'endpoint_group', limit, marker_obj = self._get_marker_obj(
marker) context, 'policy_target_group', limit, marker)
return self._get_collection(context, EndpointGroup, return self._get_collection(context, PolicyTargetGroup,
self._make_endpoint_group_dict, self._make_policy_target_group_dict,
filters=filters, fields=fields, filters=filters, fields=fields,
sorts=sorts, limit=limit, sorts=sorts, limit=limit,
marker_obj=marker_obj, marker_obj=marker_obj,
page_reverse=page_reverse) page_reverse=page_reverse)
@log.log @log.log
def get_endpoint_groups_count(self, context, filters=None): def get_policy_target_groups_count(self, context, filters=None):
return self._get_collection_count(context, EndpointGroup, return self._get_collection_count(context, PolicyTargetGroup,
filters=filters) filters=filters)
@log.log @log.log
@ -902,15 +916,15 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
@log.log @log.log
def get_network_service_policy( def get_network_service_policy(
self, context, network_service_policy_id, fields=None): self, context, network_service_policy_id, fields=None):
nsp = self._get_network_service_policy( nsp = self._get_network_service_policy(
context, network_service_policy_id) context, network_service_policy_id)
return self._make_network_service_policy_dict(nsp, fields) return self._make_network_service_policy_dict(nsp, fields)
@log.log @log.log
def get_network_service_policies( def get_network_service_policies(
self, context, filters=None, fields=None, sorts=None, limit=None, self, context, filters=None, fields=None, sorts=None, limit=None,
marker=None, page_reverse=False): marker=None, page_reverse=False):
marker_obj = self._get_marker_obj( marker_obj = self._get_marker_obj(
context, 'network_service_policy', limit, marker) context, 'network_service_policy', limit, marker)
return self._get_collection(context, NetworkServicePolicy, return self._get_collection(context, NetworkServicePolicy,
@ -1090,55 +1104,56 @@ class GroupPolicyDbPlugin(gpolicy.GroupPolicyPluginBase,
filters=filters) filters=filters)
@log.log @log.log
def create_contract(self, context, contract): def create_policy_rule_set(self, context, policy_rule_set):
ct = contract['contract'] prs = policy_rule_set['policy_rule_set']
tenant_id = self._get_tenant_id_for_create(context, ct) tenant_id = self._get_tenant_id_for_create(context, prs)
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
ct_db = Contract(id=uuidutils.generate_uuid(), prs_db = PolicyRuleSet(id=uuidutils.generate_uuid(),
tenant_id=tenant_id, tenant_id=tenant_id,
name=ct['name'], name=prs['name'],
description=ct['description']) description=prs['description'])
context.session.add(ct_db) context.session.add(prs_db)
self._set_rules_for_contract(context, ct_db, self._set_rules_for_policy_rule_set(context, prs_db,
ct['policy_rules']) prs['policy_rules'])
self._set_children_for_contract(context, ct_db, self._set_children_for_policy_rule_set(
ct['child_contracts']) context, prs_db, prs['child_policy_rule_sets'])
return self._make_contract_dict(ct_db) return self._make_policy_rule_set_dict(prs_db)
@log.log @log.log
def update_contract(self, context, contract_id, contract): def update_policy_rule_set(self, context, policy_rule_set_id,
ct = contract['contract'] policy_rule_set):
prs = policy_rule_set['policy_rule_set']
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
ct_db = self._get_contract(context, contract_id) prs_db = self._get_policy_rule_set(context, policy_rule_set_id)
if 'policy_rules' in ct: if 'policy_rules' in prs:
self._set_rules_for_contract(context, ct_db, self._set_rules_for_policy_rule_set(
ct['policy_rules']) context, prs_db, prs['policy_rules'])
del ct['policy_rules'] del prs['policy_rules']
if 'child_contracts' in ct: if 'child_policy_rule_sets' in prs:
self._set_children_for_contract(context, ct_db, self._set_children_for_policy_rule_set(
ct['child_contracts']) context, prs_db, prs['child_policy_rule_sets'])
del ct['child_contracts'] del prs['child_policy_rule_sets']
ct_db.update(ct) prs_db.update(prs)
return self._make_contract_dict(ct_db) return self._make_policy_rule_set_dict(prs_db)
@log.log @log.log
def delete_contract(self, context, contract_id): def delete_policy_rule_set(self, context, policy_rule_set_id):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
ct_db = self._get_contract(context, contract_id) prs_db = self._get_policy_rule_set(context, policy_rule_set_id)
context.session.delete(ct_db) context.session.delete(prs_db)
@log.log @log.log
def get_contract(self, context, contract_id, fields=None): def get_policy_rule_set(self, context, policy_rule_set_id, fields=None):
ct = self._get_contract(context, contract_id) prs = self._get_policy_rule_set(context, policy_rule_set_id)
return self._make_contract_dict(ct, fields) return self._make_policy_rule_set_dict(prs, fields)
@log.log @log.log
def get_contracts(self, context, filters=None, fields=None): def get_policy_rule_sets(self, context, filters=None, fields=None):
return self._get_collection(context, Contract, return self._get_collection(context, PolicyRuleSet,
self._make_contract_dict, self._make_policy_rule_set_dict,
filters=filters, fields=fields) filters=filters, fields=fields)
@log.log @log.log
def get_contracts_count(self, context, filters=None): def get_policy_rule_sets_count(self, context, filters=None):
return self._get_collection_count(context, Contract, return self._get_collection_count(context, PolicyRuleSet,
filters=filters) filters=filters)

View File

@ -24,8 +24,8 @@ from gbp.neutron.db.grouppolicy import group_policy_db as gpdb
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
class EndpointMapping(gpdb.Endpoint): class PolicyTargetMapping(gpdb.PolicyTarget):
"""Mapping of Endpoint to Neutron Port.""" """Mapping of PolicyTarget to Neutron Port."""
__table_args__ = {'extend_existing': True} __table_args__ = {'extend_existing': True}
__mapper_args__ = {'polymorphic_identity': 'mapping'} __mapper_args__ = {'polymorphic_identity': 'mapping'}
# REVISIT(ivar): Set null on delete is a temporary workaround until Nova # REVISIT(ivar): Set null on delete is a temporary workaround until Nova
@ -35,21 +35,21 @@ class EndpointMapping(gpdb.Endpoint):
nullable=True, unique=True) nullable=True, unique=True)
class EndpointGroupSubnetAssociation(model_base.BASEV2): class PTGToSubnetAssociation(model_base.BASEV2):
"""Models the many to many relation between EndpointGroup and Subnets.""" """Many to many relation between PolicyTargetGroup and Subnets."""
__tablename__ = 'gp_endpoint_group_subnet_associations' __tablename__ = 'gp_ptg_to_subnet_associations'
endpoint_group_id = sa.Column(sa.String(36), policy_target_group_id = sa.Column(
sa.ForeignKey('gp_endpoint_groups.id'), sa.String(36), sa.ForeignKey('gp_policy_target_groups.id'),
primary_key=True) primary_key=True)
subnet_id = sa.Column(sa.String(36), sa.ForeignKey('subnets.id'), subnet_id = sa.Column(sa.String(36), sa.ForeignKey('subnets.id'),
primary_key=True) primary_key=True)
class EndpointGroupMapping(gpdb.EndpointGroup): class PolicyTargetGroupMapping(gpdb.PolicyTargetGroup):
"""Mapping of EndpointGroup to set of Neutron Subnets.""" """Mapping of PolicyTargetGroup to set of Neutron Subnets."""
__table_args__ = {'extend_existing': True} __table_args__ = {'extend_existing': True}
__mapper_args__ = {'polymorphic_identity': 'mapping'} __mapper_args__ = {'polymorphic_identity': 'mapping'}
subnets = orm.relationship(EndpointGroupSubnetAssociation, subnets = orm.relationship(PTGToSubnetAssociation,
cascade='all', lazy="joined") cascade='all', lazy="joined")
@ -82,16 +82,16 @@ class GroupPolicyMappingDbPlugin(gpdb.GroupPolicyDbPlugin):
"""Group Policy Mapping interface implementation using SQLAlchemy models. """Group Policy Mapping interface implementation using SQLAlchemy models.
""" """
def _make_endpoint_dict(self, ep, fields=None): def _make_policy_target_dict(self, pt, fields=None):
res = super(GroupPolicyMappingDbPlugin, res = super(GroupPolicyMappingDbPlugin,
self)._make_endpoint_dict(ep) self)._make_policy_target_dict(pt)
res['port_id'] = ep.port_id res['port_id'] = pt.port_id
return self._fields(res, fields) return self._fields(res, fields)
def _make_endpoint_group_dict(self, epg, fields=None): def _make_policy_target_group_dict(self, ptg, fields=None):
res = super(GroupPolicyMappingDbPlugin, res = super(GroupPolicyMappingDbPlugin,
self)._make_endpoint_group_dict(epg) self)._make_policy_target_group_dict(ptg)
res['subnets'] = [subnet.subnet_id for subnet in epg.subnets] res['subnets'] = [subnet.subnet_id for subnet in ptg.subnets]
return self._fields(res, fields) return self._fields(res, fields)
def _make_l2_policy_dict(self, l2p, fields=None): def _make_l2_policy_dict(self, l2p, fields=None):
@ -106,18 +106,18 @@ class GroupPolicyMappingDbPlugin(gpdb.GroupPolicyDbPlugin):
res['routers'] = [router.router_id for router in l3p.routers] res['routers'] = [router.router_id for router in l3p.routers]
return self._fields(res, fields) return self._fields(res, fields)
def _set_port_for_endpoint(self, context, ep_id, port_id): def _set_port_for_policy_target(self, context, pt_id, port_id):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
ep_db = self._get_endpoint(context, ep_id) pt_db = self._get_policy_target(context, pt_id)
ep_db.port_id = port_id pt_db.port_id = port_id
def _add_subnet_to_endpoint_group(self, context, epg_id, subnet_id): def _add_subnet_to_policy_target_group(self, context, ptg_id, subnet_id):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
epg_db = self._get_endpoint_group(context, epg_id) ptg_db = self._get_policy_target_group(context, ptg_id)
assoc = EndpointGroupSubnetAssociation(endpoint_group_id=epg_id, assoc = PTGToSubnetAssociation(policy_target_group_id=ptg_id,
subnet_id=subnet_id) subnet_id=subnet_id)
epg_db.subnets.append(assoc) ptg_db.subnets.append(assoc)
return [subnet.subnet_id for subnet in epg_db.subnets] return [subnet.subnet_id for subnet in ptg_db.subnets]
def _set_network_for_l2_policy(self, context, l2p_id, network_id): def _set_network_for_l2_policy(self, context, l2p_id, network_id):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
@ -133,71 +133,73 @@ class GroupPolicyMappingDbPlugin(gpdb.GroupPolicyDbPlugin):
return [router.router_id for router in l3p_db.routers] return [router.router_id for router in l3p_db.routers]
@log.log @log.log
def create_endpoint(self, context, endpoint): def create_policy_target(self, context, policy_target):
ep = endpoint['endpoint'] pt = policy_target['policy_target']
tenant_id = self._get_tenant_id_for_create(context, ep) tenant_id = self._get_tenant_id_for_create(context, pt)
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
ep_db = EndpointMapping(id=uuidutils.generate_uuid(), pt_db = PolicyTargetMapping(id=uuidutils.generate_uuid(),
tenant_id=tenant_id, tenant_id=tenant_id,
name=ep['name'], name=pt['name'],
description=ep['description'], description=pt['description'],
endpoint_group_id= policy_target_group_id=
ep['endpoint_group_id'], pt['policy_target_group_id'],
port_id=ep['port_id']) port_id=pt['port_id'])
context.session.add(ep_db) context.session.add(pt_db)
return self._make_endpoint_dict(ep_db) return self._make_policy_target_dict(pt_db)
@log.log @log.log
def create_endpoint_group(self, context, endpoint_group): def create_policy_target_group(self, context, policy_target_group):
epg = endpoint_group['endpoint_group'] ptg = policy_target_group['policy_target_group']
tenant_id = self._get_tenant_id_for_create(context, epg) tenant_id = self._get_tenant_id_for_create(context, ptg)
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
epg_db = EndpointGroupMapping(id=uuidutils.generate_uuid(), ptg_db = PolicyTargetGroupMapping(id=uuidutils.generate_uuid(),
tenant_id=tenant_id, tenant_id=tenant_id,
name=epg['name'], name=ptg['name'],
description=epg['description'], description=ptg['description'],
l2_policy_id=epg['l2_policy_id'], l2_policy_id=ptg['l2_policy_id'],
network_service_policy_id= network_service_policy_id=
epg['network_service_policy_id']) ptg['network_service_policy_id'])
context.session.add(epg_db) context.session.add(ptg_db)
if 'subnets' in epg: if 'subnets' in ptg:
for subnet in epg['subnets']: for subnet in ptg['subnets']:
assoc = EndpointGroupSubnetAssociation( assoc = PTGToSubnetAssociation(
endpoint_group_id=epg_db.id, policy_target_group_id=ptg_db.id,
subnet_id=subnet subnet_id=subnet
) )
epg_db.subnets.append(assoc) ptg_db.subnets.append(assoc)
self._process_contracts_for_epg(context, epg_db, epg) self._process_policy_rule_sets_for_ptg(context, ptg_db, ptg)
return self._make_endpoint_group_dict(epg_db) return self._make_policy_target_group_dict(ptg_db)
@log.log @log.log
def update_endpoint_group(self, context, endpoint_group_id, def update_policy_target_group(self, context, policy_target_group_id,
endpoint_group): policy_target_group):
epg = endpoint_group['endpoint_group'] ptg = policy_target_group['policy_target_group']
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
epg_db = self._get_endpoint_group(context, endpoint_group_id) ptg_db = self._get_policy_target_group(
self._process_contracts_for_epg(context, epg_db, epg) context, policy_target_group_id)
if 'subnets' in epg: self._process_policy_rule_sets_for_ptg(context, ptg_db, ptg)
if 'subnets' in ptg:
# Add/remove associations for changes in subnets. # Add/remove associations for changes in subnets.
new_subnets = set(epg['subnets']) new_subnets = set(ptg['subnets'])
old_subnets = set(subnet.subnet_id old_subnets = set(subnet.subnet_id
for subnet in epg_db.subnets) for subnet in ptg_db.subnets)
for subnet in new_subnets - old_subnets: for subnet in new_subnets - old_subnets:
assoc = EndpointGroupSubnetAssociation( assoc = PTGToSubnetAssociation(
endpoint_group_id=endpoint_group_id, subnet_id=subnet) policy_target_group_id=policy_target_group_id,
epg_db.subnets.append(assoc) subnet_id=subnet)
ptg_db.subnets.append(assoc)
for subnet in old_subnets - new_subnets: for subnet in old_subnets - new_subnets:
assoc = (context.session. assoc = (
query(EndpointGroupSubnetAssociation). context.session.query(
filter_by(endpoint_group_id=endpoint_group_id, PTGToSubnetAssociation).filter_by(
subnet_id=subnet). policy_target_group_id=policy_target_group_id,
one()) subnet_id=subnet).one())
epg_db.subnets.remove(assoc) ptg_db.subnets.remove(assoc)
context.session.delete(assoc) context.session.delete(assoc)
# Don't update epg_db.subnets with subnet IDs. # Don't update ptg_db.subnets with subnet IDs.
del epg['subnets'] del ptg['subnets']
epg_db.update(epg) ptg_db.update(ptg)
return self._make_endpoint_group_dict(epg_db) return self._make_policy_target_group_dict(ptg_db)
@log.log @log.log
def create_l2_policy(self, context, l2_policy): def create_l2_policy(self, context, l2_policy):

View File

@ -13,7 +13,7 @@
# under the License. # under the License.
# #
"""gbp_contracts """gbp_policy_rule_sets
Revision ID: 3ef186997b02 Revision ID: 3ef186997b02
Create Date: 2014-07-30 14:48:49.838182 Create Date: 2014-07-30 14:48:49.838182
@ -30,49 +30,58 @@ import sqlalchemy as sa
def upgrade(): def upgrade():
op.create_table( op.create_table(
'gp_contracts', 'gp_policy_rule_sets',
sa.Column('id', sa.String(36), nullable=False), sa.Column('id', sa.String(36), nullable=False),
sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('tenant_id', sa.String(length=255), nullable=True),
sa.Column('name', sa.String(length=50), nullable=True), sa.Column('name', sa.String(length=50), nullable=True),
sa.Column('description', sa.String(length=255), nullable=True), sa.Column('description', sa.String(length=255), nullable=True),
sa.Column('parent_id', sa.String(length=36), nullable=True), sa.Column('parent_id', sa.String(length=36), nullable=True),
sa.ForeignKeyConstraint(['parent_id'], sa.ForeignKeyConstraint(['parent_id'],
['gp_contracts.id']), ['gp_policy_rule_sets.id']),
sa.PrimaryKeyConstraint('id')) sa.PrimaryKeyConstraint('id'))
op.create_table( op.create_table(
'gp_endpoint_group_contract_providing_associations', 'gp_ptg_to_prs_providing_associations',
sa.Column('contract_id', sa.String(length=36), nullable=True), sa.Column('policy_rule_set_id', sa.String(length=36), nullable=True),
sa.ForeignKeyConstraint(['contract_id'], sa.ForeignKeyConstraint(['policy_rule_set_id'],
['gp_contracts.id'], ondelete='CASCADE'), ['gp_policy_rule_sets.id'],
sa.Column('endpoint_group_id', sa.String(length=36), nullable=True), ondelete='CASCADE'),
sa.ForeignKeyConstraint(['endpoint_group_id'], sa.Column('policy_target_group_id', sa.String(length=36),
['gp_endpoint_groups.id'], ondelete='CASCADE'), nullable=True),
sa.PrimaryKeyConstraint('contract_id', 'endpoint_group_id')) sa.ForeignKeyConstraint(['policy_target_group_id'],
['gp_policy_target_groups.id'],
ondelete='CASCADE'),
sa.PrimaryKeyConstraint('policy_rule_set_id',
'policy_target_group_id'))
op.create_table( op.create_table(
'gp_endpoint_group_contract_consuming_associations', 'gp_ptg_to_prs_consuming_associations',
sa.Column('contract_id', sa.String(length=36), nullable=True), sa.Column('policy_rule_set_id', sa.String(length=36), nullable=True),
sa.ForeignKeyConstraint(['contract_id'], sa.ForeignKeyConstraint(['policy_rule_set_id'],
['gp_contracts.id'], ondelete='CASCADE'), ['gp_policy_rule_sets.id'],
sa.Column('endpoint_group_id', sa.String(length=36), nullable=True), ondelete='CASCADE'),
sa.ForeignKeyConstraint(['endpoint_group_id'], sa.Column('policy_target_group_id', sa.String(length=36),
['gp_endpoint_groups.id'], ondelete='CASCADE'), nullable=True),
sa.PrimaryKeyConstraint('contract_id', 'endpoint_group_id')) sa.ForeignKeyConstraint(['policy_target_group_id'],
['gp_policy_target_groups.id'],
ondelete='CASCADE'),
sa.PrimaryKeyConstraint('policy_rule_set_id',
'policy_target_group_id'))
op.create_table( op.create_table(
'gp_contract_policy_rule_associations', 'gp_prs_to_pr_associations',
sa.Column('contract_id', sa.String(length=36), nullable=True), sa.Column('policy_rule_set_id', sa.String(length=36), nullable=True),
sa.ForeignKeyConstraint(['contract_id'], sa.ForeignKeyConstraint(['policy_rule_set_id'],
['gp_contracts.id'], ondelete='CASCADE'), ['gp_policy_rule_sets.id'],
ondelete='CASCADE'),
sa.Column('policy_rule_id', sa.String(length=36), nullable=True), sa.Column('policy_rule_id', sa.String(length=36), nullable=True),
sa.ForeignKeyConstraint(['policy_rule_id'], sa.ForeignKeyConstraint(['policy_rule_id'],
['gp_policy_rules.id'], ondelete='CASCADE'), ['gp_policy_rules.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('contract_id', 'policy_rule_id')) sa.PrimaryKeyConstraint('policy_rule_set_id', 'policy_rule_id'))
def downgrade(): def downgrade():
op.drop_table('gp_endpoint_group_contract_providing_associations') op.drop_table('gp_ptg_to_prs_consuming_associations')
op.drop_table('gp_endpoint_group_contract_consuming_associations') op.drop_table('gp_ptg_to_prs_providing_associations')
op.drop_table('gp_contract_policy_rule_associations') op.drop_table('gp_prs_to_pr_associations')
op.drop_table('gp_contracts') op.drop_table('gp_policy_rule_sets')

View File

@ -33,13 +33,14 @@ import sqlalchemy as sa
def upgrade(): def upgrade():
op.create_table( op.create_table(
'gp_endpoint_group_subnet_associations', 'gp_ptg_to_subnet_associations',
sa.Column('endpoint_group_id', sa.String(length=36), nullable=False), sa.Column('policy_target_group_id', sa.String(length=36),
nullable=False),
sa.Column('subnet_id', sa.String(length=36), nullable=False), sa.Column('subnet_id', sa.String(length=36), nullable=False),
sa.ForeignKeyConstraint(['endpoint_group_id'], sa.ForeignKeyConstraint(['policy_target_group_id'],
['gp_endpoint_groups.id']), ['gp_policy_target_groups.id']),
sa.ForeignKeyConstraint(['subnet_id'], ['subnets.id']), sa.ForeignKeyConstraint(['subnet_id'], ['subnets.id']),
sa.PrimaryKeyConstraint('endpoint_group_id', 'subnet_id') sa.PrimaryKeyConstraint('policy_target_group_id', 'subnet_id')
) )
op.create_table( op.create_table(
@ -52,12 +53,12 @@ def upgrade():
) )
op.add_column( op.add_column(
'gp_endpoint_groups', 'gp_policy_target_groups',
sa.Column('type', sa.String(length=15), nullable=True) sa.Column('type', sa.String(length=15), nullable=True)
) )
op.add_column( op.add_column(
'gp_endpoints', 'gp_policy_targets',
sa.Column('type', sa.String(length=15), nullable=True) sa.Column('type', sa.String(length=15), nullable=True)
) )
@ -72,12 +73,12 @@ def upgrade():
) )
op.add_column( op.add_column(
'gp_endpoints', 'gp_policy_targets',
sa.Column('port_id', sa.String(length=36), nullable=True) sa.Column('port_id', sa.String(length=36), nullable=True)
) )
op.create_unique_constraint(None, 'gp_endpoints', ['port_id']) op.create_unique_constraint(None, 'gp_policy_targets', ['port_id'])
op.create_foreign_key('gp_endpoints_ibfk_2', op.create_foreign_key('gp_policy_targets_ibfk_2',
source='gp_endpoints', referent='ports', source='gp_policy_targets', referent='ports',
local_cols=['port_id'], remote_cols=['id'], local_cols=['port_id'], remote_cols=['id'],
ondelete='SET NULL') ondelete='SET NULL')
@ -95,11 +96,12 @@ def downgrade():
op.drop_constraint('gp_l2_policies_ibfk_2', 'gp_l2_policies', 'foreignkey') op.drop_constraint('gp_l2_policies_ibfk_2', 'gp_l2_policies', 'foreignkey')
op.drop_column('gp_l2_policies', 'network_id') op.drop_column('gp_l2_policies', 'network_id')
op.drop_constraint('gp_endpoints_ibfk_2', 'gp_endpoints', 'foreignkey') op.drop_constraint('gp_policy_targets_ibfk_2', 'gp_policy_targets',
op.drop_column('gp_endpoints', 'port_id') 'foreignkey')
op.drop_column('gp_policy_targets', 'port_id')
op.drop_column('gp_l3_policies', 'type') op.drop_column('gp_l3_policies', 'type')
op.drop_column('gp_l2_policies', 'type') op.drop_column('gp_l2_policies', 'type')
op.drop_column('gp_endpoints', 'type') op.drop_column('gp_policy_targets', 'type')
op.drop_column('gp_endpoint_groups', 'type') op.drop_column('gp_policy_target_groups', 'type')
op.drop_table('gp_l3_policy_router_associations') op.drop_table('gp_l3_policy_router_associations')
op.drop_table('gp_endpoint_group_subnet_associations') op.drop_table('gp_ptg_to_subnet_associations')

View File

@ -54,14 +54,14 @@ def upgrade():
sa.PrimaryKeyConstraint('id')) sa.PrimaryKeyConstraint('id'))
op.add_column( op.add_column(
'gp_endpoint_groups', 'gp_policy_target_groups',
sa.Column('network_service_policy_id', sa.Column('network_service_policy_id',
sa.String(length=36), nullable=True)) sa.String(length=36), nullable=True))
op.create_unique_constraint(None, 'gp_endpoint_groups', op.create_unique_constraint(None, 'gp_policy_target_groups',
['network_service_policy_id']) ['network_service_policy_id'])
op.create_foreign_key('gp_endpoint_groups_ibfk_nsp', op.create_foreign_key('gp_policy_target_groups_ibfk_nsp',
source='gp_endpoint_groups', source='gp_policy_target_groups',
referent='gp_network_service_policies', referent='gp_network_service_policies',
local_cols=['network_service_policy_id'], local_cols=['network_service_policy_id'],
remote_cols=['id'], ondelete='CASCADE') remote_cols=['id'], ondelete='CASCADE')
@ -69,8 +69,9 @@ def upgrade():
def downgrade(): def downgrade():
op.drop_constraint('gp_endpoint_groups_ibfk_nsp', 'gp_endpoint_groups', op.drop_constraint('gp_policy_target_groups_ibfk_nsp',
'gp_policy_target_groups',
'foreignkey') 'foreignkey')
op.drop_column('gp_endpoint_groups', 'network_service_policy_id') op.drop_column('gp_policy_target_groups', 'network_service_policy_id')
op.drop_table('gp_network_service_params') op.drop_table('gp_network_service_params')
op.drop_table('gp_network_service_policies') op.drop_table('gp_network_service_policies')

View File

@ -32,18 +32,19 @@ import sqlalchemy as sa
def upgrade(): def upgrade():
op.create_table( op.create_table(
'gpm_contract_sg_mapping', 'gpm_policy_rule_set_sg_mapping',
sa.Column('contract_id', sa.String(length=36), nullable=False), sa.Column('policy_rule_set_id', sa.String(length=36), nullable=False),
sa.Column('provided_sg_id', sa.String(length=36)), sa.Column('provided_sg_id', sa.String(length=36)),
sa.Column('consumed_sg_id', sa.String(length=36)), sa.Column('consumed_sg_id', sa.String(length=36)),
sa.ForeignKeyConstraint(['contract_id'], ['gp_contracts.id'], sa.ForeignKeyConstraint(['policy_rule_set_id'],
['gp_policy_rule_sets.id'],
ondelete='CASCADE'), ondelete='CASCADE'),
sa.ForeignKeyConstraint(['provided_sg_id'], ['securitygroups.id']), sa.ForeignKeyConstraint(['provided_sg_id'], ['securitygroups.id']),
sa.ForeignKeyConstraint(['consumed_sg_id'], ['securitygroups.id']), sa.ForeignKeyConstraint(['consumed_sg_id'], ['securitygroups.id']),
sa.PrimaryKeyConstraint('contract_id') sa.PrimaryKeyConstraint('policy_rule_set_id')
) )
def downgrade(): def downgrade():
op.drop_table('gpm_contract_sg_mapping') op.drop_table('gpm_policy_rule_set_sg_mapping')

View File

@ -13,7 +13,7 @@
# under the License. # under the License.
# #
""" gbp_db_ep_epg_l2_l3_policy """ gbp_db_ep_ptg_l2_l3_policy
Revision ID: ab64381ee820 Revision ID: ab64381ee820
""" """
@ -52,7 +52,7 @@ def upgrade():
sa.PrimaryKeyConstraint('id')) sa.PrimaryKeyConstraint('id'))
op.create_table( op.create_table(
'gp_endpoint_groups', 'gp_policy_target_groups',
sa.Column('id', sa.String(36), nullable=False), sa.Column('id', sa.String(36), nullable=False),
sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('tenant_id', sa.String(length=255), nullable=True),
sa.Column('name', sa.String(length=50), nullable=True), sa.Column('name', sa.String(length=50), nullable=True),
@ -63,20 +63,22 @@ def upgrade():
sa.PrimaryKeyConstraint('id')) sa.PrimaryKeyConstraint('id'))
op.create_table( op.create_table(
'gp_endpoints', 'gp_policy_targets',
sa.Column('id', sa.String(36), nullable=False), sa.Column('id', sa.String(36), nullable=False),
sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('tenant_id', sa.String(length=255), nullable=True),
sa.Column('name', sa.String(length=50), nullable=True), sa.Column('name', sa.String(length=50), nullable=True),
sa.Column('description', sa.String(length=255), nullable=True), sa.Column('description', sa.String(length=255), nullable=True),
sa.Column('endpoint_group_id', sa.String(length=36), nullable=True), sa.Column('policy_target_group_id', sa.String(length=36),
sa.ForeignKeyConstraint(['endpoint_group_id'], nullable=True),
['gp_endpoint_groups.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['policy_target_group_id'],
['gp_policy_target_groups.id'],
ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')) sa.PrimaryKeyConstraint('id'))
def downgrade(): def downgrade():
op.drop_table('gp_endpoints') op.drop_table('gp_policy_targets')
op.drop_table('gp_endpoint_groups') op.drop_table('gp_policy_target_groups')
op.drop_table('gp_l2_policies') op.drop_table('gp_l2_policies')
op.drop_table('gp_l3_policies') op.drop_table('gp_l3_policies')

View File

@ -34,10 +34,11 @@ def upgrade(active_plugins=None, options=None):
'gpm_service_policy_ipaddress_mappings', 'gpm_service_policy_ipaddress_mappings',
sa.Column('service_policy_id', sa.String(length=36), nullable=False), sa.Column('service_policy_id', sa.String(length=36), nullable=False),
sa.Column('ipaddress', sa.String(length=36)), sa.Column('ipaddress', sa.String(length=36)),
sa.Column('endpoint_group', sa.String(length=36)), sa.Column('policy_target_group', sa.String(length=36)),
sa.PrimaryKeyConstraint('endpoint_group'), sa.PrimaryKeyConstraint('policy_target_group'),
sa.ForeignKeyConstraint(['endpoint_group'], sa.ForeignKeyConstraint(['policy_target_group'],
['gp_endpoint_groups.id'], ondelete='CASCADE'), ['gp_policy_target_groups.id'],
ondelete='CASCADE'),
sa.PrimaryKeyConstraint('service_policy_id'), sa.PrimaryKeyConstraint('service_policy_id'),
sa.ForeignKeyConstraint(['service_policy_id'], sa.ForeignKeyConstraint(['service_policy_id'],
['gp_network_service_policies.id'], ['gp_network_service_policies.id'],

View File

@ -60,16 +60,18 @@ def upgrade(active_plugins=None, options=None):
sa.Column('description', sa.String(length=255), nullable=True), sa.Column('description', sa.String(length=255), nullable=True),
sa.Column('config_param_values', sa.String(length=4096), sa.Column('config_param_values', sa.String(length=4096),
nullable=True), nullable=True),
sa.Column('provider_epg', sa.String(length=36), nullable=True), sa.Column('provider_ptg', sa.String(length=36), nullable=True),
sa.Column('consumer_epg', sa.String(length=36), nullable=True), sa.Column('consumer_ptg', sa.String(length=36), nullable=True),
sa.Column('classifier', sa.String(length=36), nullable=True), sa.Column('classifier', sa.String(length=36), nullable=True),
sa.Column('servicechain_spec', sa.String(length=36), nullable=True), sa.Column('servicechain_spec', sa.String(length=36), nullable=True),
#FixMe(Magesh) Deletes the instances table itself !!! # FixMe(Magesh) Deletes the instances table itself !!!
#sa.ForeignKeyConstraint(['provider_epg'], ['gp_endpoint_groups.id'], # sa.ForeignKeyConstraint(['provider_ptg'],
# ondelete='CASCADE'), # ['gp_policy_target_groups.id'],
#sa.ForeignKeyConstraint(['consumer_epg'], ['gp_endpoint_groups.id'], # ondelete='CASCADE'),
# ondelete='CASCADE'), # sa.ForeignKeyConstraint(['consumer_ptg'],
#sa.ForeignKeyConstraint(['classifier'], ['gp_policy_classifiers.id'], # ['gp_policy_target_groups.id'],
# ondelete='CASCADE'),
# sa.ForeignKeyConstraint(['classifier'], ['gp_policy_classifiers.id'],
# ondelete='CASCADE'), # ondelete='CASCADE'),
sa.ForeignKeyConstraint(['servicechain_spec'], ['sc_specs.id']), sa.ForeignKeyConstraint(['servicechain_spec'], ['sc_specs.id']),
sa.PrimaryKeyConstraint('id') sa.PrimaryKeyConstraint('id')

View File

@ -33,9 +33,8 @@ MAX_IPV6_SUBNET_PREFIX_LENGTH = 127
class SpecNodeAssociation(model_base.BASEV2): class SpecNodeAssociation(model_base.BASEV2):
"""Models many to many providing relation between Specs and Nodes.""" """Models many to many providing relation between Specs and Nodes."""
__tablename__ = 'sc_spec_node_associations' __tablename__ = 'sc_spec_node_associations'
servicechain_spec = sa.Column(sa.String(36), servicechain_spec = sa.Column(
sa.ForeignKey('sc_specs.id'), sa.String(36), sa.ForeignKey('sc_specs.id'), primary_key=True)
primary_key=True)
node_id = sa.Column(sa.String(36), node_id = sa.Column(sa.String(36),
sa.ForeignKey('sc_nodes.id'), sa.ForeignKey('sc_nodes.id'),
primary_key=True) primary_key=True)
@ -61,18 +60,17 @@ class ServiceChainInstance(model_base.BASEV2, models_v2.HasId,
name = sa.Column(sa.String(50)) name = sa.Column(sa.String(50))
description = sa.Column(sa.String(255)) description = sa.Column(sa.String(255))
config_param_values = sa.Column(sa.String(4096)) config_param_values = sa.Column(sa.String(4096))
servicechain_spec = sa.Column(sa.String(36), servicechain_spec = sa.Column(
sa.ForeignKey('sc_specs.id'), sa.String(36), sa.ForeignKey('sc_specs.id'), nullable=True)
nullable=True) provider_ptg = sa.Column(sa.String(36),
provider_epg = sa.Column(sa.String(36), # FixMe(Magesh) Deletes the instances table itself
#FixMe(Magesh) Deletes the instances table itself # sa.ForeignKey('gp_policy_target_groups.id'),
#sa.ForeignKey('gp_endpoint_groups.id'),
nullable=True) nullable=True)
consumer_epg = sa.Column(sa.String(36), consumer_ptg = sa.Column(sa.String(36),
#sa.ForeignKey('gp_endpoint_groups.id'), # sa.ForeignKey('gp_policy_target_groups.id'),
nullable=True) nullable=True)
classifier = sa.Column(sa.String(36), classifier = sa.Column(sa.String(36),
#sa.ForeignKey('gp_policy_classifiers.id'), # sa.ForeignKey('gp_policy_classifiers.id'),
nullable=True) nullable=True)
@ -120,7 +118,7 @@ class ServiceChainDbPlugin(schain.ServiceChainPluginBase,
return self._get_by_id(context, ServiceChainInstance, instance_id) return self._get_by_id(context, ServiceChainInstance, instance_id)
except exc.NoResultFound: except exc.NoResultFound:
raise schain.ServiceChainInstanceNotFound( raise schain.ServiceChainInstanceNotFound(
sc_instance_id=instance_id) sc_instance_id=instance_id)
def _make_sc_node_dict(self, sc_node, fields=None): def _make_sc_node_dict(self, sc_node, fields=None):
res = {'id': sc_node['id'], res = {'id': sc_node['id'],
@ -147,8 +145,8 @@ class ServiceChainDbPlugin(schain.ServiceChainPluginBase,
'description': instance['description'], 'description': instance['description'],
'config_param_values': instance['config_param_values'], 'config_param_values': instance['config_param_values'],
'servicechain_spec': instance['servicechain_spec'], 'servicechain_spec': instance['servicechain_spec'],
'provider_epg': instance['provider_epg'], 'provider_ptg': instance['provider_ptg'],
'consumer_epg': instance['consumer_epg'], 'consumer_ptg': instance['consumer_ptg'],
'classifier': instance['classifier']} 'classifier': instance['classifier']}
return self._fields(res, fields) return self._fields(res, fields)
@ -249,7 +247,7 @@ class ServiceChainDbPlugin(schain.ServiceChainPluginBase,
spec_db.config_param_names = str(config_params.keys()) spec_db.config_param_names = str(config_params.keys())
else: else:
config_param_names = ast.literal_eval( config_param_names = ast.literal_eval(
spec_db.config_param_names) spec_db.config_param_names)
config_param_names.extend(config_params.keys()) config_param_names.extend(config_params.keys())
spec_db.config_param_names = str(config_param_names) spec_db.config_param_names = str(config_param_names)
@ -318,17 +316,14 @@ class ServiceChainDbPlugin(schain.ServiceChainPluginBase,
tenant_id = self._get_tenant_id_for_create(context, instance) tenant_id = self._get_tenant_id_for_create(context, instance)
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
instance_db = ServiceChainInstance( instance_db = ServiceChainInstance(
id=uuidutils.generate_uuid(), id=uuidutils.generate_uuid(),
tenant_id=tenant_id, tenant_id=tenant_id, name=instance['name'],
name=instance['name'], description=instance['description'],
description=instance['description'], config_param_values=instance['config_param_values'],
config_param_values=instance[ servicechain_spec=instance['servicechain_spec'],
'config_param_values'], provider_ptg=instance['provider_ptg'],
servicechain_spec=instance[ consumer_ptg=instance['consumer_ptg'],
'servicechain_spec'], classifier=instance['classifier'])
provider_epg=instance['provider_epg'],
consumer_epg=instance['consumer_epg'],
classifier=instance['classifier'])
context.session.add(instance_db) context.session.add(instance_db)
return self._make_sc_instance_dict(instance_db) return self._make_sc_instance_dict(instance_db)
@ -338,8 +333,7 @@ class ServiceChainDbPlugin(schain.ServiceChainPluginBase,
instance = servicechain_instance['servicechain_instance'] instance = servicechain_instance['servicechain_instance']
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
instance_db = self._get_servicechain_instance( instance_db = self._get_servicechain_instance(
context, context, servicechain_instance_id)
servicechain_instance_id)
instance_db.update(instance) instance_db.update(instance)
return self._make_sc_instance_dict(instance_db) return self._make_sc_instance_dict(instance_db)
@ -347,8 +341,7 @@ class ServiceChainDbPlugin(schain.ServiceChainPluginBase,
def delete_servicechain_instance(self, context, servicechain_instance_id): def delete_servicechain_instance(self, context, servicechain_instance_id):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
instance_db = self._get_servicechain_instance( instance_db = self._get_servicechain_instance(
context, context, servicechain_instance_id)
servicechain_instance_id)
context.session.delete(instance_db) context.session.delete(instance_db)
@log.log @log.log

View File

@ -40,12 +40,13 @@ LOG = logging.getLogger(__name__)
# Group Policy Exceptions # Group Policy Exceptions
class EndpointNotFound(nexc.NotFound): class PolicyTargetNotFound(nexc.NotFound):
message = _("Endpoint %(endpoint_id)s could not be found") message = _("Policy Target %(policy_target_id)s could not be found")
class EndpointGroupNotFound(nexc.NotFound): class PolicyTargetGroupNotFound(nexc.NotFound):
message = _("EndpointGroup %(endpoint_group_id)s could not be found") message = _("Policy Target Group %(policy_target_group_id)s could not "
"be found")
class L2PolicyNotFound(nexc.NotFound): class L2PolicyNotFound(nexc.NotFound):
@ -78,20 +79,20 @@ class PolicyRuleNotFound(nexc.NotFound):
message = _("PolicyRule %(policy_rule_id)s could not be found") message = _("PolicyRule %(policy_rule_id)s could not be found")
class ContractNotFound(nexc.NotFound): class PolicyRuleSetNotFound(nexc.NotFound):
message = _("Contract %(contract_id)s could not be found") message = _("Policy Rule Set %(policy_rule_set_id)s could not be found")
class BadContractRelationship(nexc.BadRequest): class BadPolicyRuleSetRelationship(nexc.BadRequest):
message = _("Contract %(parent_id)s is an invalid parent for " message = _("Policy Rule Set %(parent_id)s is an invalid parent for "
"%(child_id)s, make sure that child contract has no " "%(child_id)s, make sure that child policy_rule_set has no "
"children, or that you are not creating a relationship loop") "children, or that you are not creating a relationship loop")
class ThreeLevelContractHierarchyNotSupported(nexc.BadRequest): class ThreeLevelPolicyRuleSetHierarchyNotSupported(nexc.BadRequest):
message = _("Can't add children to contract %(contract_id)s " message = _("Can't add children to policy_rule_set %(policy_rule_set_id)s "
"which already has a parent. Only one level of contract " "which already has a parent. Only one level "
"hierarchy supported.") "of policy_rule_set hierarchy supported.")
class GroupPolicyInvalidPortValue(nexc.InvalidInput): class GroupPolicyInvalidPortValue(nexc.InvalidInput):
@ -229,19 +230,19 @@ attr.validators['type:port_range'] = _validate_port_range
attr.validators['type:network_service_params'] = _validate_network_svc_params attr.validators['type:network_service_params'] = _validate_network_svc_params
ENDPOINTS = 'endpoints' POLICY_TARGETS = 'policy_targets'
ENDPOINT_GROUPS = 'endpoint_groups' POLICY_TARGET_GROUPS = 'policy_target_groups'
L2_POLICIES = 'l2_policies' L2_POLICIES = 'l2_policies'
L3_POLICIES = 'l3_policies' L3_POLICIES = 'l3_policies'
POLICY_CLASSIFIERS = 'policy_classifiers' POLICY_CLASSIFIERS = 'policy_classifiers'
POLICY_ACTIONS = 'policy_actions' POLICY_ACTIONS = 'policy_actions'
POLICY_RULES = 'policy_rules' POLICY_RULES = 'policy_rules'
CONTRACTS = 'contracts' POLICY_RULE_SETS = 'policy_rule_sets'
NETWORK_SERVICE_POLICIES = 'network_service_policies' NETWORK_SERVICE_POLICIES = 'network_service_policies'
RESOURCE_ATTRIBUTE_MAP = { RESOURCE_ATTRIBUTE_MAP = {
ENDPOINTS: { POLICY_TARGETS: {
'id': {'allow_post': False, 'allow_put': False, 'id': {'allow_post': False, 'allow_put': False,
'validate': {'type:uuid': None}, 'is_visible': True, 'validate': {'type:uuid': None}, 'is_visible': True,
'primary_key': True}, 'primary_key': True},
@ -254,11 +255,11 @@ RESOURCE_ATTRIBUTE_MAP = {
'tenant_id': {'allow_post': True, 'allow_put': False, 'tenant_id': {'allow_post': True, 'allow_put': False,
'validate': {'type:string': None}, 'validate': {'type:string': None},
'required_by_policy': True, 'is_visible': True}, 'required_by_policy': True, 'is_visible': True},
'endpoint_group_id': {'allow_post': True, 'allow_put': True, 'policy_target_group_id': {'allow_post': True, 'allow_put': True,
'validate': {'type:uuid_or_none': None}, 'validate': {'type:uuid_or_none': None},
'required': True, 'is_visible': True}, 'required': True, 'is_visible': True},
}, },
ENDPOINT_GROUPS: { POLICY_TARGET_GROUPS: {
'id': {'allow_post': False, 'allow_put': False, 'id': {'allow_post': False, 'allow_put': False,
'validate': {'type:uuid': None}, 'is_visible': True, 'validate': {'type:uuid': None}, 'is_visible': True,
'primary_key': True}, 'primary_key': True},
@ -271,21 +272,23 @@ RESOURCE_ATTRIBUTE_MAP = {
'tenant_id': {'allow_post': True, 'allow_put': False, 'tenant_id': {'allow_post': True, 'allow_put': False,
'validate': {'type:string': None}, 'validate': {'type:string': None},
'required_by_policy': True, 'is_visible': True}, 'required_by_policy': True, 'is_visible': True},
'endpoints': {'allow_post': False, 'allow_put': False, 'policy_targets': {'allow_post': False, 'allow_put': False,
'validate': {'type:uuid_list': None}, 'validate': {'type:uuid_list': None},
'convert_to': attr.convert_none_to_empty_list, 'convert_to': attr.convert_none_to_empty_list,
'default': None, 'is_visible': True}, 'default': None, 'is_visible': True},
'l2_policy_id': {'allow_post': True, 'allow_put': True, 'l2_policy_id': {'allow_post': True, 'allow_put': True,
'validate': {'type:uuid_or_none': None}, 'validate': {'type:uuid_or_none': None},
'default': None, 'is_visible': True}, 'default': None, 'is_visible': True},
'provided_contracts': {'allow_post': True, 'allow_put': True, 'provided_policy_rule_sets': {'allow_post': True, 'allow_put': True,
'validate': {'type:dict_or_none': None}, 'validate': {'type:dict_or_none': None},
'convert_to': attr.convert_none_to_empty_dict, 'convert_to':
'default': None, 'is_visible': True}, attr.convert_none_to_empty_dict,
'consumed_contracts': {'allow_post': True, 'allow_put': True, 'default': None, 'is_visible': True},
'validate': {'type:dict_or_none': None}, 'consumed_policy_rule_sets': {'allow_post': True, 'allow_put': True,
'convert_to': attr.convert_none_to_empty_dict, 'validate': {'type:dict_or_none': None},
'default': None, 'is_visible': True}, 'convert_to':
attr.convert_none_to_empty_dict,
'default': None, 'is_visible': True},
'network_service_policy_id': {'allow_post': True, 'allow_put': True, 'network_service_policy_id': {'allow_post': True, 'allow_put': True,
'validate': {'type:uuid_or_none': None}, 'validate': {'type:uuid_or_none': None},
'default': None, 'is_visible': True}, 'default': None, 'is_visible': True},
@ -303,10 +306,10 @@ RESOURCE_ATTRIBUTE_MAP = {
'tenant_id': {'allow_post': True, 'allow_put': False, 'tenant_id': {'allow_post': True, 'allow_put': False,
'validate': {'type:string': None}, 'validate': {'type:string': None},
'required_by_policy': True, 'is_visible': True}, 'required_by_policy': True, 'is_visible': True},
'endpoint_groups': {'allow_post': False, 'allow_put': False, 'policy_target_groups': {'allow_post': False, 'allow_put': False,
'validate': {'type:uuid_list': None}, 'validate': {'type:uuid_list': None},
'convert_to': attr.convert_none_to_empty_list, 'convert_to': attr.convert_none_to_empty_list,
'default': None, 'is_visible': True}, 'default': None, 'is_visible': True},
'l3_policy_id': {'allow_post': True, 'allow_put': True, 'l3_policy_id': {'allow_post': True, 'allow_put': True,
'validate': {'type:uuid_or_none': None}, 'validate': {'type:uuid_or_none': None},
'default': None, 'is_visible': True, 'default': None, 'is_visible': True,
@ -420,7 +423,7 @@ RESOURCE_ATTRIBUTE_MAP = {
'validate': {'type:uuid_list': None}, 'validate': {'type:uuid_list': None},
'convert_to': attr.convert_none_to_empty_list}, 'convert_to': attr.convert_none_to_empty_list},
}, },
CONTRACTS: { POLICY_RULE_SETS: {
'id': {'allow_post': False, 'allow_put': False, 'id': {'allow_post': False, 'allow_put': False,
'validate': {'type:uuid': None}, 'validate': {'type:uuid': None},
'is_visible': True, 'is_visible': True,
@ -439,10 +442,11 @@ RESOURCE_ATTRIBUTE_MAP = {
'parent_id': {'allow_post': False, 'allow_put': False, 'parent_id': {'allow_post': False, 'allow_put': False,
'validate': {'type:uuid': None}, 'validate': {'type:uuid': None},
'is_visible': True}, 'is_visible': True},
'child_contracts': {'allow_post': True, 'allow_put': True, 'child_policy_rule_sets': {'allow_post': True, 'allow_put': True,
'default': None, 'is_visible': True, 'default': None, 'is_visible': True,
'validate': {'type:uuid_list': None}, 'validate': {'type:uuid_list': None},
'convert_to': attr.convert_none_to_empty_list}, 'convert_to':
attr.convert_none_to_empty_list},
'policy_rules': {'allow_post': True, 'allow_put': True, 'policy_rules': {'allow_post': True, 'allow_put': True,
'default': None, 'validate': {'type:uuid_list': None}, 'default': None, 'validate': {'type:uuid_list': None},
'convert_to': attr.convert_none_to_empty_list, 'convert_to': attr.convert_none_to_empty_list,
@ -461,10 +465,10 @@ RESOURCE_ATTRIBUTE_MAP = {
'tenant_id': {'allow_post': True, 'allow_put': False, 'tenant_id': {'allow_post': True, 'allow_put': False,
'validate': {'type:string': None}, 'validate': {'type:string': None},
'required_by_policy': True, 'is_visible': True}, 'required_by_policy': True, 'is_visible': True},
'endpoint_groups': {'allow_post': False, 'allow_put': False, 'policy_target_groups': {'allow_post': False, 'allow_put': False,
'validate': {'type:uuid_list': None}, 'validate': {'type:uuid_list': None},
'convert_to': attr.convert_none_to_empty_list, 'convert_to': attr.convert_none_to_empty_list,
'default': None, 'is_visible': True}, 'default': None, 'is_visible': True},
'network_service_params': {'allow_post': True, 'allow_put': False, 'network_service_params': {'allow_post': True, 'allow_put': False,
'validate': 'validate':
{'type:network_service_params': None}, {'type:network_service_params': None},
@ -535,44 +539,45 @@ class GroupPolicyPluginBase(service_base.ServicePluginBase):
return 'Group Policy plugin' return 'Group Policy plugin'
@abc.abstractmethod @abc.abstractmethod
def get_endpoints(self, context, filters=None, fields=None): def get_policy_targets(self, context, filters=None, fields=None):
pass pass
@abc.abstractmethod @abc.abstractmethod
def get_endpoint(self, context, endpoint_id, fields=None): def get_policy_target(self, context, policy_target_id, fields=None):
pass pass
@abc.abstractmethod @abc.abstractmethod
def create_endpoint(self, context, endpoint): def create_policy_target(self, context, policy_target):
pass pass
@abc.abstractmethod @abc.abstractmethod
def update_endpoint(self, context, endpoint_id, endpoint): def update_policy_target(self, context, policy_target_id, policy_target):
pass pass
@abc.abstractmethod @abc.abstractmethod
def delete_endpoint(self, context, endpoint_id): def delete_policy_target(self, context, policy_target_id):
pass pass
@abc.abstractmethod @abc.abstractmethod
def get_endpoint_groups(self, context, filters=None, fields=None): def get_policy_target_groups(self, context, filters=None, fields=None):
pass pass
@abc.abstractmethod @abc.abstractmethod
def get_endpoint_group(self, context, endpoint_group_id, fields=None): def get_policy_target_group(self, context, policy_target_group_id,
fields=None):
pass pass
@abc.abstractmethod @abc.abstractmethod
def create_endpoint_group(self, context, endpoint_group): def create_policy_target_group(self, context, policy_target_group):
pass pass
@abc.abstractmethod @abc.abstractmethod
def update_endpoint_group(self, context, endpoint_group_id, def update_policy_target_group(self, context, policy_target_group_id,
endpoint_group): policy_target_group):
pass pass
@abc.abstractmethod @abc.abstractmethod
def delete_endpoint_group(self, context, endpoint_group_id): def delete_policy_target_group(self, context, policy_target_group_id):
pass pass
@abc.abstractmethod @abc.abstractmethod
@ -701,21 +706,22 @@ class GroupPolicyPluginBase(service_base.ServicePluginBase):
pass pass
@abc.abstractmethod @abc.abstractmethod
def create_contract(self, context, contract): def create_policy_rule_set(self, context, policy_rule_set):
pass pass
@abc.abstractmethod @abc.abstractmethod
def update_contract(self, context, contract_id, contract): def update_policy_rule_set(self, context, policy_rule_set_id,
policy_rule_set):
pass pass
@abc.abstractmethod @abc.abstractmethod
def get_contracts(self, context, filters=None, fields=None): def get_policy_rule_sets(self, context, filters=None, fields=None):
pass pass
@abc.abstractmethod @abc.abstractmethod
def get_contract(self, context, contract_id, fields=None): def get_policy_rule_set(self, context, policy_rule_set_id, fields=None):
pass pass
@abc.abstractmethod @abc.abstractmethod
def delete_contract(self, context, contract_id): def delete_policy_rule_set(self, context, policy_rule_set_id):
pass pass

View File

@ -17,12 +17,12 @@ from gbp.neutron.extensions import group_policy as gp
# Extended attributes for Group Policy resource to map to Neutron constructs # Extended attributes for Group Policy resource to map to Neutron constructs
EXTENDED_ATTRIBUTES_2_0 = { EXTENDED_ATTRIBUTES_2_0 = {
gp.ENDPOINTS: { gp.POLICY_TARGETS: {
'port_id': {'allow_post': True, 'allow_put': False, 'port_id': {'allow_post': True, 'allow_put': False,
'validate': {'type:uuid_or_none': None}, 'validate': {'type:uuid_or_none': None},
'is_visible': True, 'default': None}, 'is_visible': True, 'default': None},
}, },
gp.ENDPOINT_GROUPS: { gp.POLICY_TARGET_GROUPS: {
'subnets': {'allow_post': True, 'allow_put': True, 'subnets': {'allow_post': True, 'allow_put': True,
'validate': {'type:uuid_list': None}, 'validate': {'type:uuid_list': None},
'convert_to': attr.convert_none_to_empty_list, 'convert_to': attr.convert_none_to_empty_list,

View File

@ -149,11 +149,11 @@ RESOURCE_ATTRIBUTE_MAP = {
'validate': {'type:uuid_or_none': None}, 'validate': {'type:uuid_or_none': None},
'default': None, 'is_visible': True, 'default': None, 'is_visible': True,
'required': True}, 'required': True},
'provider_epg': {'allow_post': True, 'allow_put': False, 'provider_ptg': {'allow_post': True, 'allow_put': False,
'validate': {'type:uuid_or_none': None}, 'validate': {'type:uuid_or_none': None},
'is_visible': True, 'default': None, 'is_visible': True, 'default': None,
'required': True}, 'required': True},
'consumer_epg': {'allow_post': True, 'allow_put': False, 'consumer_ptg': {'allow_post': True, 'allow_put': False,
'validate': {'type:uuid_or_none': None}, 'validate': {'type:uuid_or_none': None},
'is_visible': True, 'default': None, 'is_visible': True, 'default': None,
'required': True}, 'required': True},
@ -162,8 +162,8 @@ RESOURCE_ATTRIBUTE_MAP = {
'is_visible': True, 'default': None, 'is_visible': True, 'default': None,
'required': True}, 'required': True},
'config_param_values': {'allow_post': True, 'allow_put': False, 'config_param_values': {'allow_post': True, 'allow_put': False,
'validate': {'type:string': None}, 'validate': {'type:string': None},
'default': "", 'is_visible': True}, 'default': "", 'is_visible': True},
}, },
} }

View File

@ -38,7 +38,7 @@ class APICMechanismGBPDriver(api.MechanismDriver):
# DHCP Ports are created implicitly by Neutron, need to inform GBP # DHCP Ports are created implicitly by Neutron, need to inform GBP
if (context.current.get('device_owner') == if (context.current.get('device_owner') ==
n_constants.DEVICE_OWNER_DHCP): n_constants.DEVICE_OWNER_DHCP):
self.apic_gbp.create_dhcp_endpoint_if_needed( self.apic_gbp.create_dhcp_policy_target_if_needed(
context._plugin_context, context.current) context._plugin_context, context.current)
def update_port_postcommit(self, context): def update_port_postcommit(self, context):

View File

@ -38,16 +38,19 @@ class GroupPolicyBadRequest(exceptions.BadRequest, GroupPolicyException):
pass pass
class EndpointRequiresEndpointGroup(GroupPolicyBadRequest): class PolicyTargetRequiresPolicyTargetGroup(GroupPolicyBadRequest):
message = _("An endpoint group was not specified when creating endpoint.") message = _("An policy target group was not specified when "
"creating policy_target.")
class EndpointEndpointGroupUpdateNotSupported(GroupPolicyBadRequest): class PolicyTargetGroupUpdateOfPolicyTargetNotSupported(GroupPolicyBadRequest):
message = _("Updating endpoint's endpoint group is not supported.") message = _("Updating policy target group of policy target "
"is not supported.")
class EndpointGroupSubnetRemovalNotSupported(GroupPolicyBadRequest): class PolicyTargetGroupSubnetRemovalNotSupported(GroupPolicyBadRequest):
message = _("Removing a subnet from an endpoint group is not supported.") message = _("Removing a subnet from an policy target group is not "
"supported.")
class L3PolicyMultipleRoutersNotSupported(GroupPolicyBadRequest): class L3PolicyMultipleRoutersNotSupported(GroupPolicyBadRequest):
@ -62,5 +65,5 @@ class NoSubnetAvailable(exceptions.ResourceExhausted, GroupPolicyException):
message = _("No subnet is available from l3 policy's pool.") message = _("No subnet is available from l3 policy's pool.")
class EndpointGroupInUse(GroupPolicyBadRequest): class PolicyTargetGroupInUse(GroupPolicyBadRequest):
message = _("Endpoint Group %(endpoint_group)s is in use") message = _("Policy Target Group %(policy_target_group)s is in use")

View File

@ -32,10 +32,10 @@ from gbp.neutron.services.grouppolicy.drivers import resource_mapping as api
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
class L2PolicyMultipleEndpointGroupNotSupportedOnApicDriver( class L2PolicyMultiplePolicyTargetGroupNotSupportedOnApicDriver(
gpexc.GroupPolicyBadRequest): gpexc.GroupPolicyBadRequest):
message = _("An L2 policy can't have multiple endpoint groups on APIC " message = _("An L2 policy can't have multiple policy target groups on "
"GBP driver.") "APIC GBP driver.")
class RedirectActionNotSupportedOnApicDriver(gpexc.GroupPolicyBadRequest): class RedirectActionNotSupportedOnApicDriver(gpexc.GroupPolicyBadRequest):
@ -108,48 +108,49 @@ class ApicMappingDriver(api.ResourceMappingDriver):
port_id = (kwargs.get('port_id') or port_id = (kwargs.get('port_id') or
self._core_plugin._device_to_port_id(kwargs['device'])) self._core_plugin._device_to_port_id(kwargs['device']))
port = self._core_plugin.get_port(context, port_id) port = self._core_plugin.get_port(context, port_id)
# retrieve EPG and network from a given Port # retrieve PTG and network from a given Port
if not kwargs.get('endpoint'): if not kwargs.get('policy_target'):
epg, network = self._port_to_epg_network(context, port, ptg, network = self._port_to_ptg_network(context, port,
kwargs['host']) kwargs['host'])
if not epg: if not ptg:
return return
else: else:
ep = kwargs['endpoint'] pt = kwargs['policy_target']
epg = self.gbp_plugin.get_endpoint_group(context, ptg = self.gbp_plugin.get_policy_target_group(
ep['endpoint_group_id']) context, pt['policy_target_group_id'])
network = self._l2p_id_to_network(context, epg['l2_policy_id']) network = self._l2p_id_to_network(context, ptg['l2_policy_id'])
return {'port_id': port_id, return {'port_id': port_id,
'mac_address': port['mac_address'], 'mac_address': port['mac_address'],
'epg_id': epg['id'], 'ptg_id': ptg['id'],
'segmentation_id': network[pn.SEGMENTATION_ID], 'segmentation_id': network[pn.SEGMENTATION_ID],
'network_type': network[pn.NETWORK_TYPE], 'network_type': network[pn.NETWORK_TYPE],
'l2_policy_id': epg['l2_policy_id'], 'l2_policy_id': ptg['l2_policy_id'],
'tenant_id': port['tenant_id'], 'tenant_id': port['tenant_id'],
'host': port['binding:host_id'] 'host': port['binding:host_id']
} }
def create_dhcp_endpoint_if_needed(self, plugin_context, port): def create_dhcp_policy_target_if_needed(self, plugin_context, port):
session = plugin_context.session session = plugin_context.session
if (self._port_is_owned(session, port['id'])): if (self._port_is_owned(session, port['id'])):
# Nothing to do # Nothing to do
return return
# Retrieve EPG # Retrieve PTG
filters = {'network_id': [port['network_id']]} filters = {'network_id': [port['network_id']]}
epgs = self.gbp_plugin.get_endpoint_groups(plugin_context, ptgs = self.gbp_plugin.get_policy_target_groups(
filters=filters) plugin_context, filters=filters)
if epgs: if ptgs:
epg = epgs[0] ptg = ptgs[0]
# Create Endpoint # Create PolicyTarget
attrs = {'endpoint': attrs = {'policy_target':
{'tenant_id': port['tenant_id'], {'tenant_id': port['tenant_id'],
'name': 'dhcp-%s' % epg['id'], 'name': 'dhcp-%s' % ptg['id'],
'description': _("Implicitly created DHCP endpoint"), 'description': _("Implicitly created DHCP policy "
'endpoint_group_id': epg['id'], "target"),
'policy_target_group_id': ptg['id'],
'port_id': port['id']}} 'port_id': port['id']}}
self.gbp_plugin.create_endpoint(plugin_context, attrs) self.gbp_plugin.create_policy_target(plugin_context, attrs)
sg_id = self._ensure_default_security_group(plugin_context, sg_id = self._ensure_default_security_group(plugin_context,
port['tenant_id']) port['tenant_id'])
data = {'port': {'security_groups': [sg_id]}} data = {'port': {'security_groups': [sg_id]}}
@ -188,42 +189,46 @@ class ApicMappingDriver(api.ResourceMappingDriver):
self.apic_manager.create_tenant_filter(policy_rule, owner=tenant, self.apic_manager.create_tenant_filter(policy_rule, owner=tenant,
**attrs) **attrs)
def create_contract_postcommit(self, context): def create_policy_rule_set_postcommit(self, context):
# Create APIC contract # Create APIC contract
tenant = self.name_mapper.tenant(context, context.current['tenant_id']) tenant = self.name_mapper.tenant(context, context.current['tenant_id'])
contract = self.name_mapper.contract(context, context.current['id']) contract = self.name_mapper.policy_rule_set(context,
context.current['id'])
with self.apic_manager.apic.transaction(None) as trs: with self.apic_manager.apic.transaction(None) as trs:
self.apic_manager.create_contract(contract, owner=tenant, self.apic_manager.create_contract(
transaction=trs) contract, owner=tenant, transaction=trs)
self._apply_contract_rules(context, context.current, self._apply_policy_rule_set_rules(
context.current['policy_rules'], context, context.current, context.current['policy_rules'],
transaction=trs) transaction=trs)
def create_endpoint_postcommit(self, context): def create_policy_target_postcommit(self, context):
# The path needs to be created at bind time, this will be taken # The path needs to be created at bind time, this will be taken
# care by the GBP ML2 apic driver. # care by the GBP ML2 apic driver.
super(ApicMappingDriver, self).create_endpoint_postcommit(context) super(ApicMappingDriver, self).create_policy_target_postcommit(context)
self._manage_endpoint_port(context._plugin_context, context.current) self._manage_policy_target_port(
context._plugin_context, context.current)
def create_endpoint_group_postcommit(self, context): def create_policy_target_group_postcommit(self, context):
super(ApicMappingDriver, self).create_endpoint_group_postcommit( super(ApicMappingDriver, self).create_policy_target_group_postcommit(
context) context)
tenant = self.name_mapper.tenant(context, context.current['tenant_id']) tenant = self.name_mapper.tenant(context, context.current['tenant_id'])
l2_policy = self.name_mapper.l2_policy(context, l2_policy = self.name_mapper.l2_policy(context,
context.current['l2_policy_id']) context.current['l2_policy_id'])
epg = self.name_mapper.endpoint_group(context, context.current['id']) ptg = self.name_mapper.policy_target_group(context,
context.current['id'])
with self.apic_manager.apic.transaction(None) as trs: with self.apic_manager.apic.transaction(None) as trs:
self.apic_manager.ensure_epg_created(tenant, epg, self.apic_manager.ensure_epg_created(tenant, ptg,
bd_name=l2_policy) bd_name=l2_policy)
subnets = self._subnet_ids_to_objects(context._plugin_context, subnets = self._subnet_ids_to_objects(context._plugin_context,
context.current['subnets']) context.current['subnets'])
self._manage_epg_subnets(context._plugin_context, context.current, self._manage_ptg_subnets(context._plugin_context, context.current,
subnets, [], transaction=trs) subnets, [], transaction=trs)
self._manage_epg_contracts( self._manage_ptg_policy_rule_sets(
context._plugin_context, context.current, context._plugin_context, context.current,
context.current['provided_contracts'], context.current['provided_policy_rule_sets'],
context.current['consumed_contracts'], [], [], transaction=trs) context.current['consumed_policy_rule_sets'], [], [],
transaction=trs)
def create_l2_policy_postcommit(self, context): def create_l2_policy_postcommit(self, context):
super(ApicMappingDriver, self).create_l2_policy_postcommit(context) super(ApicMappingDriver, self).create_l2_policy_postcommit(context)
@ -249,37 +254,39 @@ class ApicMappingDriver(api.ResourceMappingDriver):
context.current['id']) context.current['id'])
self.apic_manager.delete_tenant_filter(policy_rule, owner=tenant) self.apic_manager.delete_tenant_filter(policy_rule, owner=tenant)
def delete_contract_precommit(self, context): def delete_policy_rule_set_precommit(self, context):
# Intercept Parent Call # Intercept Parent Call
pass pass
def delete_contract_postcommit(self, context): def delete_policy_rule_set_postcommit(self, context):
# TODO(ivar): disassociate EPGs to avoid reference leak # TODO(ivar): disassociate EPGs to avoid reference leak
tenant = self.name_mapper.tenant(context, context.current['tenant_id']) tenant = self.name_mapper.tenant(context, context.current['tenant_id'])
contract = self.name_mapper.contract(context, context.current['id']) policy_rule_set = self.name_mapper.policy_rule_set(
self.apic_manager.delete_contract(contract, owner=tenant) context, context.current['id'])
self.apic_manager.delete_contract(policy_rule_set, owner=tenant)
def delete_endpoint_postcommit(self, context): def delete_policy_target_postcommit(self, context):
port = self._core_plugin.get_port(context._plugin_context, port = self._core_plugin.get_port(context._plugin_context,
context.current['port_id']) context.current['port_id'])
if port['binding:host_id']: if port['binding:host_id']:
self.process_path_deletion(context._plugin_context, port, self.process_path_deletion(context._plugin_context, port,
endpoint=context.current) policy_target=context.current)
# Delete Neutron's port # Delete Neutron's port
super(ApicMappingDriver, self).delete_endpoint_postcommit(context) super(ApicMappingDriver, self).delete_policy_target_postcommit(context)
def delete_endpoint_group_postcommit(self, context): def delete_policy_target_group_postcommit(self, context):
if context.current['subnets']: if context.current['subnets']:
subnets = self._subnet_ids_to_objects(context._plugin_context, subnets = self._subnet_ids_to_objects(context._plugin_context,
context.current['subnets']) context.current['subnets'])
self._manage_epg_subnets(context._plugin_context, context.current, self._manage_ptg_subnets(context._plugin_context, context.current,
[], subnets) [], subnets)
for subnet_id in context.current['subnets']: for subnet_id in context.current['subnets']:
self._cleanup_subnet(context._plugin_context, subnet_id, None) self._cleanup_subnet(context._plugin_context, subnet_id, None)
tenant = self.name_mapper.tenant(context, context.current['tenant_id']) tenant = self.name_mapper.tenant(context, context.current['tenant_id'])
epg = self.name_mapper.endpoint_group(context, context.current['id']) ptg = self.name_mapper.policy_target_group(context,
context.current['id'])
self.apic_manager.delete_epg_for_network(tenant, epg) self.apic_manager.delete_epg_for_network(tenant, ptg)
def delete_l2_policy_postcommit(self, context): def delete_l2_policy_postcommit(self, context):
super(ApicMappingDriver, self).delete_l2_policy_postcommit(context) super(ApicMappingDriver, self).delete_l2_policy_postcommit(context)
@ -294,7 +301,7 @@ class ApicMappingDriver(api.ResourceMappingDriver):
self.apic_manager.ensure_context_deleted(tenant, l3_policy) self.apic_manager.ensure_context_deleted(tenant, l3_policy)
def update_endpoint_postcommit(self, context): def update_policy_target_postcommit(self, context):
# TODO(ivar): redo binding procedure if the EPG is modified, # TODO(ivar): redo binding procedure if the EPG is modified,
# not doable unless driver extension framework is in place # not doable unless driver extension framework is in place
pass pass
@ -303,21 +310,29 @@ class ApicMappingDriver(api.ResourceMappingDriver):
# TODO(ivar): add support for action update on policy rules # TODO(ivar): add support for action update on policy rules
raise PolicyRuleUpdateNotSupportedOnApicDriver() raise PolicyRuleUpdateNotSupportedOnApicDriver()
def update_endpoint_group_postcommit(self, context): def update_policy_target_group_postcommit(self, context):
# TODO(ivar): refactor parent to avoid code duplication # TODO(ivar): refactor parent to avoid code duplication
orig_provided_contracts = context.original['provided_contracts'] orig_provided_policy_rule_sets = context.original[
curr_provided_contracts = context.current['provided_contracts'] 'provided_policy_rule_sets']
orig_consumed_contracts = context.original['consumed_contracts'] curr_provided_policy_rule_sets = context.current[
curr_consumed_contracts = context.current['consumed_contracts'] 'provided_policy_rule_sets']
orig_consumed_policy_rule_sets = context.original[
'consumed_policy_rule_sets']
curr_consumed_policy_rule_sets = context.current[
'consumed_policy_rule_sets']
new_provided_contracts = list(set(curr_provided_contracts) - new_provided_policy_rule_sets = list(
set(orig_provided_contracts)) set(curr_provided_policy_rule_sets) - set(
new_consumed_contracts = list(set(curr_consumed_contracts) - orig_provided_policy_rule_sets))
set(orig_consumed_contracts)) new_consumed_policy_rule_sets = list(
removed_provided_contracts = list(set(orig_provided_contracts) - set(curr_consumed_policy_rule_sets) - set(
set(curr_provided_contracts)) orig_consumed_policy_rule_sets))
removed_consumed_contracts = list(set(orig_consumed_contracts) - removed_provided_policy_rule_sets = list(
set(curr_consumed_contracts)) set(orig_provided_policy_rule_sets) - set(
curr_provided_policy_rule_sets))
removed_consumed_policy_rule_sets = list(
set(orig_consumed_policy_rule_sets) - set(
curr_consumed_policy_rule_sets))
orig_subnets = context.original['subnets'] orig_subnets = context.original['subnets']
curr_subnets = context.current['subnets'] curr_subnets = context.current['subnets']
@ -325,67 +340,69 @@ class ApicMappingDriver(api.ResourceMappingDriver):
removed_subnets = list(set(orig_subnets) - set(curr_subnets)) removed_subnets = list(set(orig_subnets) - set(curr_subnets))
with self.apic_manager.apic.transaction(None) as trs: with self.apic_manager.apic.transaction(None) as trs:
self._manage_epg_contracts( self._manage_ptg_policy_rule_sets(
context._plugin_context, context.current, context._plugin_context, context.current,
new_provided_contracts, new_consumed_contracts, new_provided_policy_rule_sets, new_consumed_policy_rule_sets,
removed_provided_contracts, removed_consumed_contracts, removed_provided_policy_rule_sets,
transaction=trs) removed_consumed_policy_rule_sets, transaction=trs)
new_subnets = self._subnet_ids_to_objects( new_subnets = self._subnet_ids_to_objects(
context._plugin_context, new_subnets) context._plugin_context, new_subnets)
removed_subnets = self._subnet_ids_to_objects( removed_subnets = self._subnet_ids_to_objects(
context._plugin_context, removed_subnets) context._plugin_context, removed_subnets)
self._manage_epg_subnets(context._plugin_context, context.current, self._manage_ptg_subnets(context._plugin_context, context.current,
new_subnets, removed_subnets) new_subnets, removed_subnets)
def process_subnet_changed(self, context, old, new): def process_subnet_changed(self, context, old, new):
if old['gateway_ip'] != new['gateway_ip']: if old['gateway_ip'] != new['gateway_ip']:
epg = self._subnet_to_epg(context, new['id']) ptg = self._subnet_to_ptg(context, new['id'])
if epg: if ptg:
# Is GBP owned, reflect on APIC # Is GBP owned, reflect on APIC
self._manage_epg_subnets(context, epg, [new], [old]) self._manage_ptg_subnets(context, ptg, [new], [old])
def process_port_changed(self, context, old, new): def process_port_changed(self, context, old, new):
# Port's EP can't change unless EP is deleted/created, therefore the # Port's EP can't change unless EP is deleted/created, therefore the
# binding will mostly be the same except for the host # binding will mostly be the same except for the host
if old['binding:host_id'] != new['binding:host_id']: if old['binding:host_id'] != new['binding:host_id']:
ep = self._port_id_to_ep(context, new['id']) pt = self._port_id_to_pt(context, new['id'])
if ep: if pt:
if old['binding:host_id']: if old['binding:host_id']:
self.process_path_deletion(context, old) self.process_path_deletion(context, old)
self._manage_endpoint_port(context, ep) self._manage_policy_target_port(context, pt)
def process_path_deletion(self, context, port, endpoint=None): def process_path_deletion(self, context, port, policy_target=None):
port_details = self.get_gbp_details( port_details = self.get_gbp_details(
context, port_id=port['id'], host=port['binding:host_id'], context, port_id=port['id'], host=port['binding:host_id'],
endpoint=endpoint) policy_target=policy_target)
self._delete_path_if_last(context, port_details) self._delete_path_if_last(context, port_details)
def _apply_contract_rules(self, context, contract, policy_rules, def _apply_policy_rule_set_rules(
transaction=None): self, context, policy_rule_set, policy_rules, transaction=None):
# TODO(ivar): refactor parent to avoid code duplication # TODO(ivar): refactor parent to avoid code duplication
if contract['parent_id']: if policy_rule_set['parent_id']:
parent = context._plugin.get_contract( parent = context._plugin.get_policy_rule_set(
context._plugin_context, contract['parent_id']) context._plugin_context, policy_rule_set['parent_id'])
policy_rules = policy_rules & set(parent['policy_rules']) policy_rules = policy_rules & set(parent['policy_rules'])
# Don't add rules unallowed by the parent # Don't add rules unallowed by the parent
self._manage_contract_rules(context, contract, policy_rules, self._manage_policy_rule_set_rules(
transaction=transaction) context, policy_rule_set, policy_rules, transaction=transaction)
def _remove_contract_rules(self, context, contract, policy_rules, def _remove_policy_rule_set_rules(
transaction=None): self, context, policy_rule_set, policy_rules, transaction=None):
self._manage_contract_rules(context, contract, policy_rules, self._manage_policy_rule_set_rules(
unset=True, transaction=transaction) context, policy_rule_set, policy_rules, unset=True,
transaction=transaction)
def _manage_contract_rules(self, context, contract, policy_rules, def _manage_policy_rule_set_rules(
unset=False, transaction=None): self, context, policy_rule_set, policy_rules, unset=False,
transaction=None):
# REVISIT(ivar): figure out what should be moved in apicapi instead # REVISIT(ivar): figure out what should be moved in apicapi instead
if policy_rules: if policy_rules:
tenant = self.name_mapper.tenant(context, tenant = self.name_mapper.tenant(context,
context.current['tenant_id']) context.current['tenant_id'])
contract = self.name_mapper.contract(context, policy_rule_set = self.name_mapper.policy_rule_set(
context.current['id']) context, context.current['id'])
in_dir = [g_const.GP_DIRECTION_BI, g_const.GP_DIRECTION_IN] in_dir = [g_const.GP_DIRECTION_BI, g_const.GP_DIRECTION_IN]
out_dir = [g_const.GP_DIRECTION_BI, g_const.GP_DIRECTION_OUT] out_dir = [g_const.GP_DIRECTION_BI, g_const.GP_DIRECTION_OUT]
filters = {'id': policy_rules} filters = {'id': policy_rules}
@ -395,20 +412,21 @@ class ApicMappingDriver(api.ResourceMappingDriver):
classifier = context._plugin.get_policy_classifier( classifier = context._plugin.get_policy_classifier(
context._plugin_context, rule['policy_classifier_id']) context._plugin_context, rule['policy_classifier_id'])
with self.apic_manager.apic.transaction(transaction) as trs: with self.apic_manager.apic.transaction(transaction) as trs:
mgr = self.apic_manager
if classifier['direction'] in in_dir: if classifier['direction'] in in_dir:
# Contract and subject are the same thing in this case # Contract and subject are the same thing in this case
self.apic_manager.manage_contract_subject_in_filter( mgr.manage_contract_subject_in_filter(
contract, contract, policy_rule, owner=tenant, policy_rule_set, policy_rule_set, policy_rule,
transaction=trs, unset=unset) owner=tenant, transaction=trs, unset=unset)
if classifier['direction'] in out_dir: if classifier['direction'] in out_dir:
# Contract and subject are the same thing in this case # Contract and subject are the same thing in this case
self.apic_manager.manage_contract_subject_out_filter( mgr.manage_contract_subject_out_filter(
contract, contract, policy_rule, owner=tenant, policy_rule_set, policy_rule_set, policy_rule,
transaction=trs, unset=unset) owner=tenant, transaction=trs, unset=unset)
@lockutils.synchronized('apic-portlock') @lockutils.synchronized('apic-portlock')
def _manage_endpoint_port(self, plugin_context, ep): def _manage_policy_target_port(self, plugin_context, pt):
port = self._core_plugin.get_port(plugin_context, ep['port_id']) port = self._core_plugin.get_port(plugin_context, pt['port_id'])
if port.get('binding:host_id'): if port.get('binding:host_id'):
port_details = self.get_gbp_details( port_details = self.get_gbp_details(
plugin_context, port_id=port['id'], plugin_context, port_id=port['id'],
@ -419,28 +437,28 @@ class ApicMappingDriver(api.ResourceMappingDriver):
plugin_context._plugin_context = plugin_context plugin_context._plugin_context = plugin_context
tenant_id = self.name_mapper.tenant(plugin_context, tenant_id = self.name_mapper.tenant(plugin_context,
port['tenant_id']) port['tenant_id'])
epg = self.name_mapper.endpoint_group( ptg = self.name_mapper.policy_target_group(
plugin_context, port_details['epg_id']) plugin_context, port_details['ptg_id'])
bd = self.name_mapper.l2_policy( bd = self.name_mapper.l2_policy(
plugin_context, port_details['l2_policy_id']) plugin_context, port_details['l2_policy_id'])
seg = port_details['segmentation_id'] seg = port_details['segmentation_id']
# Create a static path attachment for the host/epg/switchport # Create a static path attachment for the host/epg/switchport
with self.apic_manager.apic.transaction() as trs: with self.apic_manager.apic.transaction() as trs:
self.apic_manager.ensure_path_created_for_port( self.apic_manager.ensure_path_created_for_port(
tenant_id, epg, port['binding:host_id'], seg, tenant_id, ptg, port['binding:host_id'], seg,
bd_name=bd, bd_name=bd,
transaction=trs) transaction=trs)
def _manage_epg_contracts(self, plugin_context, epg, added_provided, def _manage_ptg_policy_rule_sets(
added_consumed, removed_provided, self, plugin_context, ptg, added_provided, added_consumed,
removed_consumed, transaction=None): removed_provided, removed_consumed, transaction=None):
# TODO(ivar): change APICAPI to not expect a resource context # TODO(ivar): change APICAPI to not expect a resource context
plugin_context._plugin = self.gbp_plugin plugin_context._plugin = self.gbp_plugin
plugin_context._plugin_context = plugin_context plugin_context._plugin_context = plugin_context
mapped_tenant = self.name_mapper.tenant(plugin_context, mapped_tenant = self.name_mapper.tenant(plugin_context,
epg['tenant_id']) ptg['tenant_id'])
mapped_epg = self.name_mapper.endpoint_group(plugin_context, mapped_ptg = self.name_mapper.policy_target_group(plugin_context,
epg['id']) ptg['id'])
provided = [added_provided, removed_provided] provided = [added_provided, removed_provided]
consumed = [added_consumed, removed_consumed] consumed = [added_consumed, removed_consumed]
methods = [self.apic_manager.set_contract_for_epg, methods = [self.apic_manager.set_contract_for_epg,
@ -448,24 +466,24 @@ class ApicMappingDriver(api.ResourceMappingDriver):
with self.apic_manager.apic.transaction(transaction) as trs: with self.apic_manager.apic.transaction(transaction) as trs:
for x in xrange(len(provided)): for x in xrange(len(provided)):
for c in provided[x]: for c in provided[x]:
c = self.name_mapper.contract(plugin_context, c) c = self.name_mapper.policy_rule_set(plugin_context, c)
methods[x](mapped_tenant, mapped_epg, c, provider=True, methods[x](mapped_tenant, mapped_ptg, c, provider=True,
transaction=trs) transaction=trs)
for x in xrange(len(consumed)): for x in xrange(len(consumed)):
for c in consumed[x]: for c in consumed[x]:
c = self.name_mapper.contract(plugin_context, c) c = self.name_mapper.policy_rule_set(plugin_context, c)
methods[x](mapped_tenant, mapped_epg, c, provider=False, methods[x](mapped_tenant, mapped_ptg, c, provider=False,
transaction=trs) transaction=trs)
def _manage_epg_subnets(self, plugin_context, epg, added_subnets, def _manage_ptg_subnets(self, plugin_context, ptg, added_subnets,
removed_subnets, transaction=None): removed_subnets, transaction=None):
# TODO(ivar): change APICAPI to not expect a resource context # TODO(ivar): change APICAPI to not expect a resource context
plugin_context._plugin = self.gbp_plugin plugin_context._plugin = self.gbp_plugin
plugin_context._plugin_context = plugin_context plugin_context._plugin_context = plugin_context
mapped_tenant = self.name_mapper.tenant(plugin_context, mapped_tenant = self.name_mapper.tenant(plugin_context,
epg['tenant_id']) ptg['tenant_id'])
mapped_l2p = self.name_mapper.l2_policy(plugin_context, mapped_l2p = self.name_mapper.l2_policy(plugin_context,
epg['l2_policy_id']) ptg['l2_policy_id'])
subnets = [added_subnets, removed_subnets] subnets = [added_subnets, removed_subnets]
methods = [self.apic_manager.ensure_subnet_created_on_apic, methods = [self.apic_manager.ensure_subnet_created_on_apic,
self.apic_manager.ensure_subnet_deleted_on_apic] self.apic_manager.ensure_subnet_deleted_on_apic]
@ -483,10 +501,10 @@ class ApicMappingDriver(api.ResourceMappingDriver):
models.PortBinding.port_id != port_info['port_id']).count() models.PortBinding.port_id != port_info['port_id']).count()
@lockutils.synchronized('apic-portlock') @lockutils.synchronized('apic-portlock')
def _delete_port_path(self, context, atenant_id, epg, port_info): def _delete_port_path(self, context, atenant_id, ptg, port_info):
if not self._get_active_path_count(context, port_info): if not self._get_active_path_count(context, port_info):
self.apic_manager.ensure_path_deleted_for_port( self.apic_manager.ensure_path_deleted_for_port(
atenant_id, epg, port_info['host']) atenant_id, ptg, port_info['host'])
def _delete_path_if_last(self, context, port_info): def _delete_path_if_last(self, context, port_info):
if not self._get_active_path_count(context, port_info): if not self._get_active_path_count(context, port_info):
@ -495,8 +513,9 @@ class ApicMappingDriver(api.ResourceMappingDriver):
context._plugin_context = context context._plugin_context = context
atenant_id = self.name_mapper.tenant(context, atenant_id = self.name_mapper.tenant(context,
port_info['tenant_id']) port_info['tenant_id'])
epg = self.name_mapper.endpoint_group(context, port_info['epg_id']) ptg = self.name_mapper.policy_target_group(context,
self._delete_port_path(context, atenant_id, epg, port_info) port_info['ptg_id'])
self._delete_port_path(context, atenant_id, ptg, port_info)
def _ensure_default_security_group(self, context, tenant_id): def _ensure_default_security_group(self, context, tenant_id):
filters = {'name': ['gbp_apic_default'], 'tenant_id': [tenant_id]} filters = {'name': ['gbp_apic_default'], 'tenant_id': [tenant_id]}
@ -522,10 +541,10 @@ class ApicMappingDriver(api.ResourceMappingDriver):
else: else:
return default_group[0]['id'] return default_group[0]['id']
def _assoc_epg_sg_to_ep(self, context, ep_id, epg_id): def _assoc_ptg_sg_to_pt(self, context, pt_id, ptg_id):
pass pass
def _handle_contracts(self, context): def _handle_policy_rule_sets(self, context):
pass pass
def _gateway_ip(self, subnet): def _gateway_ip(self, subnet):
@ -536,26 +555,26 @@ class ApicMappingDriver(api.ResourceMappingDriver):
return [x for x in self._core_plugin.get_subnets( return [x for x in self._core_plugin.get_subnets(
plugin_context, filters={'id': ids})] plugin_context, filters={'id': ids})]
def _port_to_epg_network(self, context, port, host=None): def _port_to_ptg_network(self, context, port, host=None):
epg = self._port_id_to_epg(context, port['id']) ptg = self._port_id_to_ptg(context, port['id'])
if not epg: if not ptg:
# Not GBP port # Not GBP port
return None, None return None, None
network = self._l2p_id_to_network(context, epg['l2_policy_id']) network = self._l2p_id_to_network(context, ptg['l2_policy_id'])
return epg, network return ptg, network
def _port_id_to_ep(self, context, port_id): def _port_id_to_pt(self, context, port_id):
ep = (context.session.query(gpdb.EndpointMapping). pt = (context.session.query(gpdb.PolicyTargetMapping).
filter_by(port_id=port_id).first()) filter_by(port_id=port_id).first())
if ep: if pt:
db_utils = gpdb.GroupPolicyMappingDbPlugin() db_utils = gpdb.GroupPolicyMappingDbPlugin()
return db_utils._make_endpoint_dict(ep) return db_utils._make_policy_target_dict(pt)
def _port_id_to_epg(self, context, port_id): def _port_id_to_ptg(self, context, port_id):
ep = self._port_id_to_ep(context, port_id) pt = self._port_id_to_pt(context, port_id)
if ep: if pt:
return self.gbp_plugin.get_endpoint_group( return self.gbp_plugin.get_policy_target_group(
context, ep['endpoint_group_id']) context, pt['policy_target_group_id'])
return return
def _l2p_id_to_network(self, context, l2p_id): def _l2p_id_to_network(self, context, l2p_id):
@ -567,12 +586,12 @@ class ApicMappingDriver(api.ResourceMappingDriver):
context, filters={'network_id': [network_id]}) context, filters={'network_id': [network_id]})
return l2ps[0] if l2ps else None return l2ps[0] if l2ps else None
def _subnet_to_epg(self, context, subnet_id): def _subnet_to_ptg(self, context, subnet_id):
epg = (context.session.query(gpdb.EndpointGroupMapping). ptg = (context.session.query(gpdb.PolicyTargetGroupMapping).
join(gpdb.EndpointGroupMapping.subnets). join(gpdb.PolicyTargetGroupMapping.subnets).
filter(gpdb.EndpointGroupSubnetAssociation.subnet_id == filter(gpdb.PTGToSubnetAssociation.subnet_id ==
subnet_id). subnet_id).
first()) first())
if epg: if ptg:
db_utils = gpdb.GroupPolicyMappingDbPlugin() db_utils = gpdb.GroupPolicyMappingDbPlugin()
return db_utils._make_endpoint_group_dict(epg) return db_utils._make_policy_target_group_dict(ptg)

View File

@ -22,51 +22,51 @@ class NoopDriver(api.PolicyDriver):
pass pass
@log.log @log.log
def create_endpoint_precommit(self, context): def create_policy_target_precommit(self, context):
pass pass
@log.log @log.log
def create_endpoint_postcommit(self, context): def create_policy_target_postcommit(self, context):
pass pass
@log.log @log.log
def update_endpoint_precommit(self, context): def update_policy_target_precommit(self, context):
pass pass
@log.log @log.log
def update_endpoint_postcommit(self, context): def update_policy_target_postcommit(self, context):
pass pass
@log.log @log.log
def delete_endpoint_precommit(self, context): def delete_policy_target_precommit(self, context):
pass pass
@log.log @log.log
def delete_endpoint_postcommit(self, context): def delete_policy_target_postcommit(self, context):
pass pass
@log.log @log.log
def create_endpoint_group_precommit(self, context): def create_policy_target_group_precommit(self, context):
pass pass
@log.log @log.log
def create_endpoint_group_postcommit(self, context): def create_policy_target_group_postcommit(self, context):
pass pass
@log.log @log.log
def update_endpoint_group_precommit(self, context): def update_policy_target_group_precommit(self, context):
pass pass
@log.log @log.log
def update_endpoint_group_postcommit(self, context): def update_policy_target_group_postcommit(self, context):
pass pass
@log.log @log.log
def delete_endpoint_group_precommit(self, context): def delete_policy_target_group_precommit(self, context):
pass pass
@log.log @log.log
def delete_endpoint_group_postcommit(self, context): def delete_policy_target_group_postcommit(self, context):
pass pass
@log.log @log.log
@ -214,25 +214,25 @@ class NoopDriver(api.PolicyDriver):
pass pass
@log.log @log.log
def create_contract_precommit(self, context): def create_policy_rule_set_precommit(self, context):
pass pass
@log.log @log.log
def create_contract_postcommit(self, context): def create_policy_rule_set_postcommit(self, context):
pass pass
@log.log @log.log
def update_contract_precommit(self, context): def update_policy_rule_set_precommit(self, context):
pass pass
@log.log @log.log
def update_contract_postcommit(self, context): def update_policy_rule_set_postcommit(self, context):
pass pass
@log.log @log.log
def delete_contract_precommit(self, context): def delete_policy_rule_set_precommit(self, context):
pass pass
@log.log @log.log
def delete_contract_postcommit(self, context): def delete_policy_rule_set_postcommit(self, context):
pass pass

View File

@ -33,13 +33,13 @@ opts = [
cfg.StrOpt('default_ip_pool', cfg.StrOpt('default_ip_pool',
default='172.16.0.0/12', default='172.16.0.0/12',
help=_("IP pool for implicitly created default L3 policies, " help=_("IP pool for implicitly created default L3 policies, "
"from which subnets are allocated for endpoint " "from which subnets are allocated for policy target "
"groups.")), "groups.")),
cfg.IntOpt('default_subnet_prefix_length', cfg.IntOpt('default_subnet_prefix_length',
default=26, default=26,
help=_("Subnet prefix length for implicitly created default L3 " help=_("Subnet prefix length for implicitly created default L3 "
"polices, controlling size of subnets allocated for " "polices, controlling size of subnets allocated for "
"endpoint groups.")), "policy target groups.")),
] ]
cfg.CONF.register_opts(opts, "group_policy_implicit_policy") cfg.CONF.register_opts(opts, "group_policy_implicit_policy")
@ -69,7 +69,7 @@ class ImplicitPolicyDriver(api.PolicyDriver):
"""Implicit Policy driver for Group Policy plugin. """Implicit Policy driver for Group Policy plugin.
This driver ensures that the l2_policy_id attribute of This driver ensures that the l2_policy_id attribute of
EndpointGroup references an L2Policy instance and that the PolicyTargetGroup references an L2Policy instance and that the
l3_policy_id attribute of L2Policy references an L3Policy instance l3_policy_id attribute of L2Policy references an L3Policy instance
when the default value of None is specified. when the default value of None is specified.
""" """
@ -83,12 +83,12 @@ class ImplicitPolicyDriver(api.PolicyDriver):
self._default_subnet_prefix_length = gpip.default_subnet_prefix_length self._default_subnet_prefix_length = gpip.default_subnet_prefix_length
@log.log @log.log
def create_endpoint_group_postcommit(self, context): def create_policy_target_group_postcommit(self, context):
if not context.current['l2_policy_id']: if not context.current['l2_policy_id']:
self._use_implicit_l2_policy(context) self._use_implicit_l2_policy(context)
@log.log @log.log
def update_endpoint_group_postcommit(self, context): def update_policy_target_group_postcommit(self, context):
old_l2p_id = context.original['l2_policy_id'] old_l2p_id = context.original['l2_policy_id']
new_l2p_id = context.current['l2_policy_id'] new_l2p_id = context.current['l2_policy_id']
if old_l2p_id != new_l2p_id: if old_l2p_id != new_l2p_id:
@ -97,7 +97,7 @@ class ImplicitPolicyDriver(api.PolicyDriver):
self._use_implicit_l2_policy(context) self._use_implicit_l2_policy(context)
@log.log @log.log
def delete_endpoint_group_postcommit(self, context): def delete_policy_target_group_postcommit(self, context):
l2p_id = context.current['l2_policy_id'] l2p_id = context.current['l2_policy_id']
self._cleanup_l2_policy(context, l2p_id) self._cleanup_l2_policy(context, l2p_id)

View File

@ -12,10 +12,10 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from gbp.neutron.services.grouppolicy.drivers.oneconvergence import\ from gbp.neutron.services.grouppolicy.drivers import (
nvsd_gbp_api resource_mapping as res_map)
from gbp.neutron.services.grouppolicy.drivers import resource_mapping\ from gbp.neutron.services.grouppolicy.drivers.oneconvergence import (
as res_map nvsd_gbp_api as api)
from neutron.common import exceptions as n_exc from neutron.common import exceptions as n_exc
from neutron.common import log from neutron.common import log
@ -30,52 +30,51 @@ class NvsdGbpDriver(res_map.ResourceMappingDriver):
This class inherits from ResourceMappingDriver and overrides the implicit This class inherits from ResourceMappingDriver and overrides the implicit
Subnet creation for an EndPointGroup. One Convergence NVSD only supports Subnet creation for an EndPointGroup. One Convergence NVSD only supports
REDIRECT to an L2 Service at present and the Provider and Consumer EPGs REDIRECT to an L2 Service at present and the Provider and Consumer PTGs
have to be on the same network and subnet. Hence, One Convergence NVSD have to be on the same network and subnet. Hence, One Convergence NVSD
Group Policy Driver creates only one default L2 Policy for a tenant. Group Policy Driver creates only one default L2 Policy for a tenant.
Further, the EPGs do not have a one-to-one mapping to a subnet, but rather Further, the PTGs do not have a one-to-one mapping to a subnet, but rather
multiple EPGs are mapped to one subnet. One Convergence NVSD maps an EPG to multiple PTGs are mapped to one subnet. One Convergence NVSD maps an PTG to
a NVSD Port Group. a NVSD Port Group.
""" """
def __init__(self): def __init__(self):
self.nvsd_api = nvsd_gbp_api.NVSDServiceApi() self.nvsd_api = api.NVSDServiceApi()
@log.log @log.log
def create_endpoint_postcommit(self, context): def create_policy_target_postcommit(self, context):
super(NvsdGbpDriver, self).create_endpoint_postcommit(context) super(NvsdGbpDriver, self).create_policy_target_postcommit(context)
try: try:
self.nvsd_api.create_endpoint(context._plugin_context, self.nvsd_api.create_endpoint(context._plugin_context,
context.current) context.current)
except Exception: except Exception:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
super(NvsdGbpDriver, self).delete_endpoint_postcommit(context) super(NvsdGbpDriver,
self).delete_policy_target_postcommit(context)
@log.log @log.log
def update_endpoint_postcommit(self, context): def update_policy_target_postcommit(self, context):
self.nvsd_api.update_endpoint(context._plugin_context, self.nvsd_api.update_endpoint(context._plugin_context,
context.current) context.current)
@log.log @log.log
def delete_endpoint_postcommit(self, context): def delete_policy_target_postcommit(self, context):
self.nvsd_api.delete_endpoint(context._plugin_context, self.nvsd_api.delete_endpoint(context._plugin_context,
context.current['id']) context.current['id'])
super(NvsdGbpDriver, self).delete_endpoint_postcommit(context) super(NvsdGbpDriver, self).delete_policy_target_postcommit(context)
@log.log @log.log
def create_endpoint_group_precommit(self, context): def create_policy_target_group_precommit(self, context):
#Reuse the previously created implicit L2 Policy for the tenant # Reuse the previously created implicit L2 Policy for the tenant
if not context.current['l2_policy_id']: if not context.current['l2_policy_id']:
l2ps = context._plugin.get_l2_policies( l2ps = context._plugin.get_l2_policies(
context._plugin_context, context._plugin_context,
filters=({'description': filters=({'description': ["Implicitly created L2 policy"],
["Implicitly created L2 policy"], "tenant_id": [context.current['tenant_id']]}))
"tenant_id": [
context.current['tenant_id']]}))
if l2ps: if l2ps:
context.set_l2_policy_id(l2ps[0]['id']) context.set_l2_policy_id(l2ps[0]['id'])
@log.log @log.log
def create_endpoint_group_postcommit(self, context): def create_policy_target_group_postcommit(self, context):
subnets = context.current['subnets'] subnets = context.current['subnets']
if subnets: if subnets:
l2p_id = context.current['l2_policy_id'] l2p_id = context.current['l2_policy_id']
@ -91,26 +90,28 @@ class NvsdGbpDriver(res_map.ResourceMappingDriver):
self._use_implicit_subnet(context) self._use_implicit_subnet(context)
self.nvsd_api.create_endpointgroup(context._plugin_context, self.nvsd_api.create_endpointgroup(context._plugin_context,
context.current) context.current)
self._handle_contracts(context) self._handle_policy_rule_sets(context)
@log.log @log.log
def update_endpoint_group_postcommit(self, context): def update_policy_target_group_postcommit(self, context):
super(NvsdGbpDriver, self).update_endpoint_group_postcommit(context) super(NvsdGbpDriver,
self).update_policy_target_group_postcommit(context)
self.nvsd_api.update_endpointgroup(context._plugin_context, self.nvsd_api.update_endpointgroup(context._plugin_context,
context.current) context.current)
@log.log @log.log
def delete_endpoint_group_precommit(self, context): def delete_policy_target_group_precommit(self, context):
l2p_id = context.current['l2_policy_id'] l2p_id = context.current['l2_policy_id']
epgs = context._plugin.get_endpoint_groups( ptgs = context._plugin.get_policy_target_groups(
context._plugin_context, filters=({'l2_policy_id': [l2p_id]})) context._plugin_context,
for epg in epgs: filters=({'l2_policy_id': [l2p_id]}))
if epg['id'] != context.current['id']: for ptg in ptgs:
if ptg['id'] != context.current['id']:
context.current['l2_policy_id'] = None context.current['l2_policy_id'] = None
return return
@log.log @log.log
def delete_endpoint_group_postcommit(self, context): def delete_policy_target_group_postcommit(self, context):
try: try:
self._cleanup_redirect_action(context) self._cleanup_redirect_action(context)
except Exception as err: except Exception as err:
@ -122,7 +123,7 @@ class NvsdGbpDriver(res_map.ResourceMappingDriver):
for subnet_id in context.current['subnets']: for subnet_id in context.current['subnets']:
self._cleanup_subnet(context, subnet_id, router_id) self._cleanup_subnet(context, subnet_id, router_id)
except Exception as err: except Exception as err:
LOG.error(_("Cleanup of Endpoint group failed. " LOG.error(_("Cleanup of Policy target group failed. "
"Error : %s"), err) "Error : %s"), err)
self.nvsd_api.delete_endpointgroup(context._plugin_context, self.nvsd_api.delete_endpointgroup(context._plugin_context,
context.current['id']) context.current['id'])
@ -158,24 +159,25 @@ class NvsdGbpDriver(res_map.ResourceMappingDriver):
pass pass
def _use_implicit_subnet(self, context): def _use_implicit_subnet(self, context):
#One Convergence NVSD does not support REDIRECT to a different Subnet # One Convergence NVSD does not support REDIRECT to a different Subnet
#at present. So restricting to use same subnet for a given L2 Policy # at present. So restricting to use same subnet for a given L2 Policy
epgs = context._plugin.get_endpoint_groups(context._plugin_context, ptgs = context._plugin.get_policy_target_groups(
filters=({'l2_policy_id': context._plugin_context, filters=(
[context.current['l2_policy_id']]})) {'l2_policy_id': [context.current['l2_policy_id']]}))
for epg in epgs: for ptg in ptgs:
if epg['subnets']: if ptg['subnets']:
context.add_subnet(epg['subnets'][0]) context.add_subnet(ptg['subnets'][0])
return return
#Create a new Subnet for first EPG using the L2 Policy # Create a new Subnet for first PTG using the L2 Policy
super(NvsdGbpDriver, self)._use_implicit_subnet(context) super(NvsdGbpDriver, self)._use_implicit_subnet(context)
def _cleanup_subnet(self, context, subnet_id, router_id): def _cleanup_subnet(self, context, subnet_id, router_id):
#Cleanup is performed only when the last EPG on subnet is removed # Cleanup is performed only when the last PTG on subnet is removed
epgs = context._plugin.get_endpoint_groups(context._plugin_context) ptgs = context._plugin.get_policy_target_groups(
for epg in epgs: context._plugin_context)
epg_subnets = epg['subnets'] for ptg in ptgs:
if subnet_id in epg_subnets: ptg_subnets = ptg['subnets']
if subnet_id in ptg_subnets:
return return
super(NvsdGbpDriver, self)._cleanup_subnet(context._plugin_context, super(NvsdGbpDriver, self)._cleanup_subnet(context._plugin_context,
subnet_id, router_id) subnet_id, router_id)

File diff suppressed because it is too large Load Diff

View File

@ -20,59 +20,61 @@ class GroupPolicyContext(object):
self._plugin_context = plugin_context self._plugin_context = plugin_context
class EndpointContext(GroupPolicyContext, api.EndpointContext): class PolicyTargetContext(GroupPolicyContext, api.PolicyTargetContext):
def __init__(self, plugin, plugin_context, endpoint, def __init__(self, plugin, plugin_context, policy_target,
original_endpoint=None): original_policy_target=None):
super(EndpointContext, self).__init__(plugin, plugin_context) super(PolicyTargetContext, self).__init__(plugin, plugin_context)
self._endpoint = endpoint self._policy_target = policy_target
self._original_endpoint = original_endpoint self._original_policy_target = original_policy_target
@property @property
def current(self): def current(self):
return self._endpoint return self._policy_target
@property @property
def original(self): def original(self):
return self._original_endpoint return self._original_policy_target
def set_port_id(self, port_id): def set_port_id(self, port_id):
self._plugin._set_port_for_endpoint( self._plugin._set_port_for_policy_target(
self._plugin_context, self._endpoint['id'], port_id) self._plugin_context, self._policy_target['id'], port_id)
self._endpoint['port_id'] = port_id self._policy_target['port_id'] = port_id
class EndpointGroupContext(GroupPolicyContext, api.EndpointGroupContext): class PolicyTargetGroupContext(GroupPolicyContext,
api.PolicyTargetGroupContext):
def __init__(self, plugin, plugin_context, endpoint_group, def __init__(self, plugin, plugin_context, policy_target_group,
original_endpoint_group=None): original_policy_target_group=None):
super(EndpointGroupContext, self).__init__(plugin, plugin_context) super(PolicyTargetGroupContext, self).__init__(plugin, plugin_context)
self._endpoint_group = endpoint_group self._policy_target_group = policy_target_group
self._original_endpoint_group = original_endpoint_group self._original_policy_target_group = original_policy_target_group
@property @property
def current(self): def current(self):
return self._endpoint_group return self._policy_target_group
@property @property
def original(self): def original(self):
return self._original_endpoint_group return self._original_policy_target_group
def set_l2_policy_id(self, l2_policy_id): def set_l2_policy_id(self, l2_policy_id):
self._plugin._set_l2_policy_for_endpoint_group( self._plugin._set_l2_policy_for_policy_target_group(
self._plugin_context, self._endpoint_group['id'], l2_policy_id) self._plugin_context, self._policy_target_group['id'],
self._endpoint_group['l2_policy_id'] = l2_policy_id l2_policy_id)
self._policy_target_group['l2_policy_id'] = l2_policy_id
def set_network_service_policy_id(self, network_service_policy_id): def set_network_service_policy_id(self, network_service_policy_id):
nsp_id = network_service_policy_id nsp_id = network_service_policy_id
self._plugin._set_network_service_policy_for_endpoint_group( self._plugin._set_network_service_policy_for_policy_target_group(
self._plugin_context, self._endpoint_group['id'], nsp_id) self._plugin_context, self._policy_target_group['id'], nsp_id)
self._endpoint_group['network_service_policy_id'] = nsp_id self._policy_target_group['network_service_policy_id'] = nsp_id
def add_subnet(self, subnet_id): def add_subnet(self, subnet_id):
subnets = self._plugin._add_subnet_to_endpoint_group( subnets = self._plugin._add_subnet_to_policy_target_group(
self._plugin_context, self._endpoint_group['id'], subnet_id) self._plugin_context, self._policy_target_group['id'], subnet_id)
self._endpoint_group['subnets'] = subnets self._policy_target_group['subnets'] = subnets
class L2PolicyContext(GroupPolicyContext, api.L2PolicyContext): class L2PolicyContext(GroupPolicyContext, api.L2PolicyContext):
@ -194,18 +196,18 @@ class PolicyRuleContext(GroupPolicyContext, api.PolicyRuleContext):
return self._original_policy_rule return self._original_policy_rule
class ContractContext(GroupPolicyContext, api.ContractContext): class PolicyRuleSetContext(GroupPolicyContext, api.PolicyRuleSetContext):
def __init__(self, plugin, plugin_context, contract, def __init__(self, plugin, plugin_context, policy_rule_set,
original_contract=None): original_policy_rule_set=None):
super(ContractContext, self).__init__(plugin, plugin_context) super(PolicyRuleSetContext, self).__init__(plugin, plugin_context)
self._contract = contract self._policy_rule_set = policy_rule_set
self._original_contract = original_contract self._original_policy_rule_set = original_policy_rule_set
@property @property
def current(self): def current(self):
return self._contract return self._policy_rule_set
@property @property
def original(self): def original(self):
return self._original_contract return self._original_policy_rule_set

View File

@ -16,100 +16,101 @@ import six
@six.add_metaclass(abc.ABCMeta) @six.add_metaclass(abc.ABCMeta)
class EndpointContext(object): class PolicyTargetContext(object):
"""Context passed to policy engine for endpoint resource changes. """Context passed to policy engine for policy_target resource changes.
An EndpointContext instance wraps an endpoint resource. It provides A PolicyTargetContext instance wraps a policy_target resource. It provides
helper methods for accessing other relevant information. Results helper methods for accessing other relevant information. Results
from expensive operations are cached for convenient access. from expensive operations are cached for convenient access.
""" """
@abc.abstractproperty @abc.abstractproperty
def current(self): def current(self):
"""Return the current state of the endpoint. """Return the current state of the policy_target.
Return the current state of the endpoint, as defined by Return the current state of the policy_target, as defined by
GroupPolicyPlugin.create_endpoint. GroupPolicyPlugin.create_policy_target.
""" """
pass pass
@abc.abstractproperty @abc.abstractproperty
def original(self): def original(self):
"""Return the original state of the endpoint. """Return the original state of the policy_target.
Return the original state of the endpoint, prior to a call to Return the original state of the policy_target, prior to a call to
update_endpoint. Method is only valid within calls to update_policy_target. Method is only valid within calls to
update_endpoint_precommit and update_endpoint_postcommit. update_policy_target_precommit and update_policy_target_postcommit.
""" """
pass pass
@abc.abstractmethod @abc.abstractmethod
def set_port_id(self, port_id): def set_port_id(self, port_id):
"""Set the port for the endpoint. """Set the port for the policy_target.
:param port_id: Port to which endpoint is mapped. :param port_id: Port to which policy_target is mapped.
Set the neutron port to which the endpoint is mapped. Set the neutron port to which the policy_target is mapped.
""" """
pass pass
@six.add_metaclass(abc.ABCMeta) @six.add_metaclass(abc.ABCMeta)
class EndpointGroupContext(object): class PolicyTargetGroupContext(object):
"""Context passed to policy engine for endpoint_group resource changes. """Context passed to policy engine for policy_target_group resource changes.
An EndpointContext instance wraps an endpoint_group resource. It provides PolicyTargetContext instance wraps a policy_target_group resource. It
helper methods for accessing other relevant information. Results provides helper methods for accessing other relevant information. Results
from expensive operations are cached for convenient access. from expensive operations are cached for convenient access.
""" """
@abc.abstractproperty @abc.abstractproperty
def current(self): def current(self):
"""Return the current state of the endpoint_group. """Return the current state of the policy_target_group.
Return the current state of the endpoint_group, as defined by Return the current state of the policy_target_group, as defined by
GroupPolicyPlugin.create_endpoint_group. GroupPolicyPlugin.create_policy_target_group.
""" """
pass pass
@abc.abstractproperty @abc.abstractproperty
def original(self): def original(self):
"""Return the original state of the endpoint_group. """Return the original state of the policy_target_group.
Return the original state of the endpoint_group, prior to a call to Return the original state of the policy_target_group, prior to a call
update_endpoint_group. Method is only valid within calls to to update_policy_target_group. Method is only valid within calls to
update_endpoint_group_precommit and update_endpoint_group_postcommit. update_policy_target_group_precommit and
update_policy_target_group_postcommit.
""" """
pass pass
@abc.abstractmethod @abc.abstractmethod
def set_l2_policy_id(self, l2_policy_id): def set_l2_policy_id(self, l2_policy_id):
"""Set the l2_policy for the endpoint_group. """Set the l2_policy for the policy_target_group.
:param l2_policy_id: l2_policy for the endpoint_group. :param l2_policy_id: l2_policy for the policy_target_group.
Set the l2_policy for the endpoint_group. Set the l2_policy for the policy_target_group.
""" """
pass pass
@abc.abstractmethod @abc.abstractmethod
def set_network_service_policy_id(self, network_service_policy_id): def set_network_service_policy_id(self, network_service_policy_id):
"""Set the network_service_policy for the endpoint_group. """Set the network_service_policy for the policy_target_group.
:param network_service_policy_id: network_service_policy for the epg. :param network_service_policy_id: network_service_policy for the ptg.
Set the network_service_policy for the endpoint_group. Set the network_service_policy for the policy_target_group.
""" """
pass pass
@abc.abstractmethod @abc.abstractmethod
def add_subnet(self, subnet_id): def add_subnet(self, subnet_id):
"""Add the subnet to the endpoint_group. """Add the subnet to the policy_target_group.
:param subnet_id: Subnet to which endpoint_group is mapped. :param subnet_id: Subnet to which policy_target_group is mapped.
Add a neutron subnet to the set of subnets to which the Add a neutron subnet to the set of subnets to which the
endpoint_group is mapped. policy_target_group is mapped.
""" """
pass pass
@ -242,7 +243,7 @@ class NetworkServicePolicyContext(object):
class PolicyClassifierContext(object): class PolicyClassifierContext(object):
"""Context passed to policy engine for policy_classifier resource changes. """Context passed to policy engine for policy_classifier resource changes.
An PolicyClassifierContext instance wraps an policy_classifier resource. An PolicyClassifierContext instance wraps a policy_classifier resource.
It provides helper methods for accessing other relevant information. It provides helper methods for accessing other relevant information.
Results from expensive operations are cached for convenient access. Results from expensive operations are cached for convenient access.
""" """
@ -272,7 +273,7 @@ class PolicyClassifierContext(object):
class PolicyActionContext(object): class PolicyActionContext(object):
"""Context passed to policy engine for policy_action resource changes. """Context passed to policy engine for policy_action resource changes.
An PolicyActionContext instance wraps an policy_action resource. An PolicyActionContext instance wraps a policy_action resource.
It provides helper methods for accessing other relevant information. It provides helper methods for accessing other relevant information.
Results from expensive operations are cached for convenient access. Results from expensive operations are cached for convenient access.
""" """
@ -301,7 +302,7 @@ class PolicyActionContext(object):
class PolicyRuleContext(object): class PolicyRuleContext(object):
"""Context passed to policy engine for policy_rule resource changes. """Context passed to policy engine for policy_rule resource changes.
An PolicyRuleContext instance wraps an policy_rule resource. An PolicyRuleContext instance wraps a policy_rule resource.
It provides helper methods for accessing other relevant information. It provides helper methods for accessing other relevant information.
Results from expensive operations are cached for convenient access. Results from expensive operations are cached for convenient access.
""" """
@ -328,30 +329,30 @@ class PolicyRuleContext(object):
@six.add_metaclass(abc.ABCMeta) @six.add_metaclass(abc.ABCMeta)
class ContractContext(object): class PolicyRuleSetContext(object):
"""Context passed to policy engine for changes to contract resources. """Context passed to policy engine for changes to policy_rule_set resources.
An ContractContext instance wraps an contract resource. It provides PolicyRuleSetContext instance wraps a policy_rule_set resource. It
helper methods for accessing other relevant information. Results provides helper methods for accessing other relevant information. Results
from expensive operations are cached for convenient access. from expensive operations are cached for convenient access.
""" """
@abc.abstractproperty @abc.abstractproperty
def current(self): def current(self):
"""Return the current state of the contract. """Return the current state of the policy_rule_set.
Return the current state of the contract, as defined by Return the current state of the policy_rule_set, as defined by
GroupPolicyPlugin.create_contract. GroupPolicyPlugin.create_policy_rule_set.
""" """
pass pass
@abc.abstractproperty @abc.abstractproperty
def original(self): def original(self):
"""Return the original state of the contract. """Return the original state of the policy_rule_set.
Return the original state of the contract, prior to a call to Return the original state of the policy_rule_set, prior to a call to
update_contract. Method is only valid within calls to update_policy_rule_set. Method is only valid within calls to
update_contract_precommit and update_contract_postcommit. update_policy_rule_set_precommit and update_policy_rule_set_postcommit.
""" """
pass pass
@ -388,103 +389,105 @@ class PolicyDriver(object):
""" """
pass pass
def create_endpoint_precommit(self, context): def create_policy_target_precommit(self, context):
"""Allocate resources for a new endpoint. """Allocate resources for a new policy_target.
:param context: EndpointContext instance describing the new :param context: PolicyTargetContext instance describing the new
endpoint. policy_target.
""" """
pass pass
def create_endpoint_postcommit(self, context): def create_policy_target_postcommit(self, context):
"""Create a endpoint. """Create a policy_target.
:param context: EndpointContext instance describing the new :param context: PolicyTargetContext instance describing the new
endpoint. policy_target.
""" """
pass pass
def update_endpoint_precommit(self, context): def update_policy_target_precommit(self, context):
"""Update resources of a endpoint. """Update resources of a policy_target.
:param context: EndpointContext instance describing the new :param context: PolicyTargetContext instance describing the new
state of the endpoint, as well as the original state prior state of the policy_target, as well as the original state prior
to the update_endpoint call. to the update_policy_target call.
""" """
pass pass
def update_endpoint_postcommit(self, context): def update_policy_target_postcommit(self, context):
"""Update a endpoint. """Update a policy_target.
:param context: EndpointContext instance describing the new :param context: PolicyTargetContext instance describing the new
state of the endpoint, as well as the original state prior state of the policy_target, as well as the original state prior
to the update_endpoint call. to the update_policy_target call.
""" """
pass pass
def delete_endpoint_precommit(self, context): def delete_policy_target_precommit(self, context):
"""Delete resources for a endpoint. """Delete resources for a policy_target.
:param context: EndpointContext instance describing the current :param context: PolicyTargetContext instance describing the current
state of the endpoint, prior to the call to delete it. state of the policy_target, prior to the call to delete it.
""" """
pass pass
def delete_endpoint_postcommit(self, context): def delete_policy_target_postcommit(self, context):
"""Delete a endpoint. """Delete a policy_target.
:param context: EndpointContext instance describing the current :param context: PolicyTargetContext instance describing the current
state of the endpoint, prior to the call to delete it. state of the policy_target, prior to the call to delete it.
""" """
pass pass
def create_endpoint_group_precommit(self, context): def create_policy_target_group_precommit(self, context):
"""Allocate resources for a new endpoint_group. """Allocate resources for a new policy_target_group.
:param context: EndpointGroupContext instance describing the new :param context: PolicyTargetGroupContext instance describing the new
endpoint_group. policy_target_group.
""" """
pass pass
def create_endpoint_group_postcommit(self, context): def create_policy_target_group_postcommit(self, context):
"""Create a endpoint_group. """Create a policy_target_group.
:param context: EndpointGroupContext instance describing the new :param context: PolicyTargetGroupContext instance describing the new
endpoint_group. policy_target_group.
""" """
pass pass
def update_endpoint_group_precommit(self, context): def update_policy_target_group_precommit(self, context):
"""Update resources of a endpoint_group. """Update resources of a policy_target_group.
:param context: EndpointGroupContext instance describing the new :param context: PolicyTargetGroupContext instance describing the new
state of the endpoint_group, as well as the original state prior state of the policy_target_group, as well as the original state prior
to the update_endpoint_group call. to the update_policy_target_group call.
""" """
pass pass
def update_endpoint_group_postcommit(self, context): def update_policy_target_group_postcommit(self, context):
"""Update a endpoint_group. """Update a policy_target_group.
:param context: EndpointGroupContext instance describing the new :param context: PolicyTargetGroupContext instance describing the new
state of the endpoint_group, as well as the original state prior state of the policy_target_group, as well as the original state prior
to the update_endpoint_group call. to the update_policy_target_group call.
""" """
pass pass
def delete_endpoint_group_precommit(self, context): def delete_policy_target_group_precommit(self, context):
"""Delete resources for a endpoint_group. """Delete resources for a policy_target_group.
:param context: EndpointGroupContext instance describing the current :param context: PolicyTargetGroupContext instance describing the
state of the endpoint_group, prior to the call to delete it. current state of the policy_target_group, prior to the call to delete
it.
""" """
pass pass
def delete_endpoint_group_postcommit(self, context): def delete_policy_target_group_postcommit(self, context):
"""Delete a endpoint_group. """Delete a policy_target_group.
:param context: EndpointGroupContext instance describing the current :param context: PolicyTargetGroupContext instance describing the
state of the endpoint_group, prior to the call to delete it. current state of the policy_target_group, prior to the call to delete
it.
""" """
pass pass
@ -738,53 +741,53 @@ class PolicyDriver(object):
""" """
pass pass
def create_contract_precommit(self, context): def create_policy_rule_set_precommit(self, context):
"""Allocate resources for a new contract. """Allocate resources for a new policy_rule_set.
:param context: ContractContext instance describing the new :param context: PolicyRuleSetContext instance describing the new
contract. policy_rule_set.
""" """
pass pass
def create_contract_postcommit(self, context): def create_policy_rule_set_postcommit(self, context):
"""Create a contract. """Create a policy_rule_set.
:param context: ContractContext instance describing the new :param context: PolicyRuleSetContext instance describing the new
contract. policy_rule_set.
""" """
pass pass
def update_contract_precommit(self, context): def update_policy_rule_set_precommit(self, context):
"""Update resources of a contract. """Update resources of a policy_rule_set.
:param context: ContractContext instance describing the new :param context: PolicyRuleSetContext instance describing the new
state of the contract, as well as the original state prior state of the policy_rule_set, as well as the original state prior
to the update_contract call. to the update_policy_rule_set call.
""" """
pass pass
def update_contract_postcommit(self, context): def update_policy_rule_set_postcommit(self, context):
"""Update a contract. """Update a policy_rule_set.
:param context: ContractContext instance describing the new :param context: PolicyRuleSetContext instance describing the new
state of the contract, as well as the original state prior state of the policy_rule_set, as well as the original state prior
to the update_contract call. to the update_policy_rule_set call.
""" """
pass pass
def delete_contract_precommit(self, context): def delete_policy_rule_set_precommit(self, context):
"""Delete resources for a contract. """Delete resources for a policy_rule_set.
:param context: ContractContext instance describing the current :param context: PolicyRuleSetContext instance describing the current
state of the contract, prior to the call to delete it. state of the policy_rule_set, prior to the call to delete it.
""" """
pass pass
def delete_contract_postcommit(self, context): def delete_policy_rule_set_postcommit(self, context):
"""Delete a contract. """Delete a policy_rule_set.
:param context: ContractContext instance describing the current :param context: PolicyRuleSetContext instance describing the current
state of the contract, prior to the call to delete it. state of the policy_rule_set, prior to the call to delete it.
""" """
pass pass

View File

@ -39,134 +39,139 @@ class GroupPolicyPlugin(group_policy_mapping_db.GroupPolicyMappingDbPlugin):
self.policy_driver_manager.initialize() self.policy_driver_manager.initialize()
@log.log @log.log
def create_endpoint(self, context, endpoint): def create_policy_target(self, context, policy_target):
session = context.session
with session.begin(subtransactions=True):
result = super(GroupPolicyPlugin, self).create_endpoint(context,
endpoint)
policy_context = p_context.EndpointContext(self, context, result)
self.policy_driver_manager.create_endpoint_precommit(
policy_context)
try:
self.policy_driver_manager.create_endpoint_postcommit(
policy_context)
except gp_exc.GroupPolicyDriverError:
with excutils.save_and_reraise_exception():
LOG.error(_("create_endpoint_postcommit "
"failed, deleting endpoint '%s'"), result['id'])
self.delete_endpoint(context, result['id'])
return result
@log.log
def update_endpoint(self, context, endpoint_id, endpoint):
session = context.session
with session.begin(subtransactions=True):
original_endpoint = super(GroupPolicyPlugin,
self).get_endpoint(context, endpoint_id)
updated_endpoint = super(GroupPolicyPlugin,
self).update_endpoint(context,
endpoint_id,
endpoint)
policy_context = p_context.EndpointContext(
self, context, updated_endpoint,
original_endpoint=original_endpoint)
self.policy_driver_manager.update_endpoint_precommit(
policy_context)
self.policy_driver_manager.update_endpoint_postcommit(policy_context)
return updated_endpoint
@log.log
def delete_endpoint(self, context, endpoint_id):
session = context.session
with session.begin(subtransactions=True):
endpoint = self.get_endpoint(context, endpoint_id)
policy_context = p_context.EndpointContext(self, context, endpoint)
self.policy_driver_manager.delete_endpoint_precommit(
policy_context)
super(GroupPolicyPlugin, self).delete_endpoint(context,
endpoint_id)
try:
self.policy_driver_manager.delete_endpoint_postcommit(
policy_context)
except gp_exc.GroupPolicyDriverError:
with excutils.save_and_reraise_exception():
LOG.error(_("delete_endpoint_postcommit "
"failed, deleting contract '%s'"), endpoint_id)
@log.log
def create_endpoint_group(self, context, endpoint_group):
session = context.session session = context.session
with session.begin(subtransactions=True): with session.begin(subtransactions=True):
result = super(GroupPolicyPlugin, result = super(GroupPolicyPlugin,
self).create_endpoint_group(context, endpoint_group) self).create_policy_target(context, policy_target)
policy_context = p_context.EndpointGroupContext(self, context, policy_context = p_context.PolicyTargetContext(self, context,
result) result)
self.policy_driver_manager.create_endpoint_group_precommit( self.policy_driver_manager.create_policy_target_precommit(
policy_context) policy_context)
try: try:
self.policy_driver_manager.create_endpoint_group_postcommit( self.policy_driver_manager.create_policy_target_postcommit(
policy_context) policy_context)
except gp_exc.GroupPolicyDriverError: except gp_exc.GroupPolicyDriverError:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.error(_("create_endpoint_group_postcommit " LOG.error(_("create_policy_target_postcommit "
"failed, deleting endpoint_group '%s'"), "failed, deleting policy_target '%s'"),
result['id']) result['id'])
self.delete_endpoint_group(context, result['id']) self.delete_policy_target(context, result['id'])
return result return result
@log.log @log.log
def update_endpoint_group(self, context, endpoint_group_id, def update_policy_target(self, context, policy_target_id, policy_target):
endpoint_group):
session = context.session session = context.session
with session.begin(subtransactions=True): with session.begin(subtransactions=True):
original_endpoint_group = super(GroupPolicyPlugin, original_policy_target = super(
self).get_endpoint_group( GroupPolicyPlugin, self).get_policy_target(context,
context, endpoint_group_id) policy_target_id)
updated_endpoint_group = super(GroupPolicyPlugin, updated_policy_target = super(
self).update_endpoint_group( GroupPolicyPlugin, self).update_policy_target(
context, endpoint_group_id, context, policy_target_id, policy_target)
endpoint_group) policy_context = p_context.PolicyTargetContext(
policy_context = p_context.EndpointGroupContext( self, context, updated_policy_target,
self, context, updated_endpoint_group, original_policy_target=original_policy_target)
original_endpoint_group=original_endpoint_group) self.policy_driver_manager.update_policy_target_precommit(
self.policy_driver_manager.update_endpoint_group_precommit(
policy_context) policy_context)
self.policy_driver_manager.update_endpoint_group_postcommit( self.policy_driver_manager.update_policy_target_postcommit(
policy_context) policy_context)
return updated_policy_target
return updated_endpoint_group
@log.log @log.log
def delete_endpoint_group(self, context, endpoint_group_id): def delete_policy_target(self, context, policy_target_id):
session = context.session session = context.session
with session.begin(subtransactions=True): with session.begin(subtransactions=True):
endpoint_group = self.get_endpoint_group(context, policy_target = self.get_policy_target(context, policy_target_id)
endpoint_group_id) policy_context = p_context.PolicyTargetContext(
if endpoint_group['endpoints']: self, context, policy_target)
raise gp_exc.EndpointGroupInUse( self.policy_driver_manager.delete_policy_target_precommit(
endpoint_group=endpoint_group_id)
policy_context = p_context.EndpointGroupContext(self, context,
endpoint_group)
self.policy_driver_manager.delete_endpoint_group_precommit(
policy_context) policy_context)
super(GroupPolicyPlugin, self).delete_endpoint_group( super(GroupPolicyPlugin, self).delete_policy_target(
context, endpoint_group_id) context, policy_target_id)
try: try:
self.policy_driver_manager.delete_endpoint_group_postcommit( self.policy_driver_manager.delete_policy_target_postcommit(
policy_context) policy_context)
except gp_exc.GroupPolicyDriverError: except gp_exc.GroupPolicyDriverError:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.error(_("delete_endpoint_group_postcommit " LOG.error(_("delete_policy_target_postcommit "
"failed, deleting endpoint_group '%s'"), "failed, deleting policy_rule_set '%s'"),
endpoint_group_id) policy_target_id)
@log.log
def create_policy_target_group(self, context, policy_target_group):
session = context.session
with session.begin(subtransactions=True):
result = super(GroupPolicyPlugin,
self).create_policy_target_group(
context, policy_target_group)
policy_context = p_context.PolicyTargetGroupContext(
self, context, result)
self.policy_driver_manager.create_policy_target_group_precommit(
policy_context)
try:
self.policy_driver_manager.create_policy_target_group_postcommit(
policy_context)
except gp_exc.GroupPolicyDriverError:
with excutils.save_and_reraise_exception():
LOG.error(_("create_policy_target_group_postcommit "
"failed, deleting policy_target_group '%s'"),
result['id'])
self.delete_policy_target_group(context, result['id'])
return result
@log.log
def update_policy_target_group(self, context, policy_target_group_id,
policy_target_group):
session = context.session
with session.begin(subtransactions=True):
original_policy_target_group = super(
GroupPolicyPlugin, self).get_policy_target_group(
context, policy_target_group_id)
updated_policy_target_group = super(
GroupPolicyPlugin, self).update_policy_target_group(
context, policy_target_group_id, policy_target_group)
policy_context = p_context.PolicyTargetGroupContext(
self, context, updated_policy_target_group,
original_policy_target_group=original_policy_target_group)
self.policy_driver_manager.update_policy_target_group_precommit(
policy_context)
self.policy_driver_manager.update_policy_target_group_postcommit(
policy_context)
return updated_policy_target_group
@log.log
def delete_policy_target_group(self, context, policy_target_group_id):
session = context.session
with session.begin(subtransactions=True):
policy_target_group = self.get_policy_target_group(
context, policy_target_group_id)
if policy_target_group['policy_targets']:
raise gp_exc.PolicyTargetGroupInUse(
policy_target_group=policy_target_group_id)
policy_context = p_context.PolicyTargetGroupContext(
self, context, policy_target_group)
self.policy_driver_manager.delete_policy_target_group_precommit(
policy_context)
super(GroupPolicyPlugin, self).delete_policy_target_group(
context, policy_target_group_id)
try:
self.policy_driver_manager.delete_policy_target_group_postcommit(
policy_context)
except gp_exc.GroupPolicyDriverError:
with excutils.save_and_reraise_exception():
LOG.error(_("delete_policy_target_group_postcommit "
"failed, deleting policy_target_group '%s'"),
policy_target_group_id)
@log.log @log.log
def create_l2_policy(self, context, l2_policy): def create_l2_policy(self, context, l2_policy):
@ -255,8 +260,8 @@ class GroupPolicyPlugin(group_policy_mapping_db.GroupPolicyMappingDbPlugin):
return result return result
@log.log @log.log
def update_network_service_policy( def update_network_service_policy(self, context, network_service_policy_id,
self, context, network_service_policy_id, network_service_policy): network_service_policy):
session = context.session session = context.session
with session.begin(subtransactions=True): with session.begin(subtransactions=True):
original_network_service_policy = super( original_network_service_policy = super(
@ -557,58 +562,64 @@ class GroupPolicyPlugin(group_policy_mapping_db.GroupPolicyMappingDbPlugin):
" failed, deleting policy_rule '%s'"), id) " failed, deleting policy_rule '%s'"), id)
@log.log @log.log
def create_contract(self, context, contract): def create_policy_rule_set(self, context, policy_rule_set):
session = context.session session = context.session
with session.begin(subtransactions=True): with session.begin(subtransactions=True):
result = super(GroupPolicyPlugin, self).create_contract(context, result = super(GroupPolicyPlugin,
contract) self).create_policy_rule_set(
policy_context = p_context.ContractContext(self, context, result) context, policy_rule_set)
self.policy_driver_manager.create_contract_precommit( policy_context = p_context.PolicyRuleSetContext(
self, context, result)
self.policy_driver_manager.create_policy_rule_set_precommit(
policy_context) policy_context)
try: try:
self.policy_driver_manager.create_contract_postcommit( self.policy_driver_manager.create_policy_rule_set_postcommit(
policy_context) policy_context)
except gp_exc.GroupPolicyDriverError: except gp_exc.GroupPolicyDriverError:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.error(_("policy_driver_manager.create_contract_postcommit " LOG.error(_(
"failed, deleting contract '%s'"), result['id']) "policy_driver_manager.create_policy_rule_set_postcommit "
self.delete_contract(context, result['id']) "failed, deleting policy_rule_set '%s'"), result['id'])
self.delete_policy_rule_set(context, result['id'])
return result return result
@log.log @log.log
def update_contract(self, context, id, contract): def update_policy_rule_set(self, context, id, policy_rule_set):
session = context.session session = context.session
with session.begin(subtransactions=True): with session.begin(subtransactions=True):
original_contract = super(GroupPolicyPlugin, original_policy_rule_set = super(
self).get_contract(context, id) GroupPolicyPlugin, self).get_policy_rule_set(context, id)
updated_contract = super(GroupPolicyPlugin, updated_policy_rule_set = super(
self).update_contract(context, id, GroupPolicyPlugin, self).update_policy_rule_set(
contract) context, id, policy_rule_set)
policy_context = p_context.ContractContext( policy_context = p_context.PolicyRuleSetContext(
self, context, updated_contract, self, context, updated_policy_rule_set,
original_contract=original_contract) original_policy_rule_set=original_policy_rule_set)
self.policy_driver_manager.update_contract_precommit( self.policy_driver_manager.update_policy_rule_set_precommit(
policy_context) policy_context)
self.policy_driver_manager.update_contract_postcommit(policy_context) self.policy_driver_manager.update_policy_rule_set_postcommit(
return updated_contract policy_context)
return updated_policy_rule_set
@log.log @log.log
def delete_contract(self, context, id): def delete_policy_rule_set(self, context, id):
session = context.session session = context.session
with session.begin(subtransactions=True): with session.begin(subtransactions=True):
contract = self.get_contract(context, id) policy_rule_set = self.get_policy_rule_set(context, id)
policy_context = p_context.ContractContext(self, context, contract) policy_context = p_context.PolicyRuleSetContext(
self.policy_driver_manager.delete_contract_precommit( self, context, policy_rule_set)
self.policy_driver_manager.delete_policy_rule_set_precommit(
policy_context) policy_context)
super(GroupPolicyPlugin, self).delete_contract(context, id) super(GroupPolicyPlugin, self).delete_policy_rule_set(context, id)
try: try:
self.policy_driver_manager.delete_contract_postcommit( self.policy_driver_manager.delete_policy_rule_set_postcommit(
policy_context) policy_context)
except gp_exc.GroupPolicyDriverError: except gp_exc.GroupPolicyDriverError:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.error(_("policy_driver_manager.delete_contract_postcommit " LOG.error(_(
"failed, deleting contract '%s'"), id) "policy_driver_manager.delete_policy_rule_set_postcommit "
"failed, deleting policy_rule_set '%s'"), id)

View File

@ -32,10 +32,10 @@ class PolicyDriverManager(stevedore.named.NamedExtensionManager):
resources. resources.
precommit operation: precommit operation:
Notifies all policy drivers during endpoint creation. Notifies all policy drivers during policy_target creation.
Raises neutron.services.grouppolicy.common.GroupPolicyDriverError Raises neutron.services.grouppolicy.common.GroupPolicyDriverError
if any policy driver create_endpoint_precommit call fails. if any policy driver create_policy_target_precommit call fails.
Called within the database transaction. If a policy driver Called within the database transaction. If a policy driver
raises an exception, then a GroupPolicyDriverError is propogated raises an exception, then a GroupPolicyDriverError is propogated
@ -43,14 +43,14 @@ class PolicyDriverManager(stevedore.named.NamedExtensionManager):
that all policy drivers are called in this case. that all policy drivers are called in this case.
postcommit operation: postcommit operation:
Notifies all policy drivers after endpoint creation. Notifies all policy drivers after policy_target creation.
Raises neutron.services.grouppolicy.common.GroupPolicyDriverError Raises neutron.services.grouppolicy.common.GroupPolicyDriverError
if any policy driver create_endpoint_postcommit call fails. if any policy driver create_policy_target_postcommit call fails.
Called after the database transaction. If a policy driver Called after the database transaction. If a policy driver
raises an exception, then a GroupPolicyDriverError is propagated raises an exception, then a GroupPolicyDriverError is propagated
to the caller, where the endpoint will be deleted, triggering to the caller, where the policy_target will be deleted, triggering
any required cleanup. There is no guarantee that all policy any required cleanup. There is no guarantee that all policy
drivers are called in this case. drivers are called in this case.
""" """
@ -134,42 +134,42 @@ class PolicyDriverManager(stevedore.named.NamedExtensionManager):
method=method_name method=method_name
) )
def create_endpoint_precommit(self, context): def create_policy_target_precommit(self, context):
self._call_on_drivers("create_endpoint_precommit", context) self._call_on_drivers("create_policy_target_precommit", context)
def create_endpoint_postcommit(self, context): def create_policy_target_postcommit(self, context):
self._call_on_drivers("create_endpoint_postcommit", context) self._call_on_drivers("create_policy_target_postcommit", context)
def update_endpoint_precommit(self, context): def update_policy_target_precommit(self, context):
self._call_on_drivers("update_endpoint_precommit", context) self._call_on_drivers("update_policy_target_precommit", context)
def update_endpoint_postcommit(self, context): def update_policy_target_postcommit(self, context):
self._call_on_drivers("update_endpoint_postcommit", context) self._call_on_drivers("update_policy_target_postcommit", context)
def delete_endpoint_precommit(self, context): def delete_policy_target_precommit(self, context):
self._call_on_drivers("delete_endpoint_precommit", context) self._call_on_drivers("delete_policy_target_precommit", context)
def delete_endpoint_postcommit(self, context): def delete_policy_target_postcommit(self, context):
self._call_on_drivers("delete_endpoint_postcommit", context, self._call_on_drivers("delete_policy_target_postcommit", context,
continue_on_failure=True) continue_on_failure=True)
def create_endpoint_group_precommit(self, context): def create_policy_target_group_precommit(self, context):
self._call_on_drivers("create_endpoint_group_precommit", context) self._call_on_drivers("create_policy_target_group_precommit", context)
def create_endpoint_group_postcommit(self, context): def create_policy_target_group_postcommit(self, context):
self._call_on_drivers("create_endpoint_group_postcommit", context) self._call_on_drivers("create_policy_target_group_postcommit", context)
def update_endpoint_group_precommit(self, context): def update_policy_target_group_precommit(self, context):
self._call_on_drivers("update_endpoint_group_precommit", context) self._call_on_drivers("update_policy_target_group_precommit", context)
def update_endpoint_group_postcommit(self, context): def update_policy_target_group_postcommit(self, context):
self._call_on_drivers("update_endpoint_group_postcommit", context) self._call_on_drivers("update_policy_target_group_postcommit", context)
def delete_endpoint_group_precommit(self, context): def delete_policy_target_group_precommit(self, context):
self._call_on_drivers("delete_endpoint_group_precommit", context) self._call_on_drivers("delete_policy_target_group_precommit", context)
def delete_endpoint_group_postcommit(self, context): def delete_policy_target_group_postcommit(self, context):
self._call_on_drivers("delete_endpoint_group_postcommit", context, self._call_on_drivers("delete_policy_target_group_postcommit", context,
continue_on_failure=True) continue_on_failure=True)
def create_l2_policy_precommit(self, context): def create_l2_policy_precommit(self, context):
@ -292,21 +292,21 @@ class PolicyDriverManager(stevedore.named.NamedExtensionManager):
self._call_on_drivers("delete_policy_rule_postcommit", context, self._call_on_drivers("delete_policy_rule_postcommit", context,
continue_on_failure=True) continue_on_failure=True)
def create_contract_precommit(self, context): def create_policy_rule_set_precommit(self, context):
self._call_on_drivers("create_contract_precommit", context) self._call_on_drivers("create_policy_rule_set_precommit", context)
def create_contract_postcommit(self, context): def create_policy_rule_set_postcommit(self, context):
self._call_on_drivers("create_contract_postcommit", context) self._call_on_drivers("create_policy_rule_set_postcommit", context)
def update_contract_precommit(self, context): def update_policy_rule_set_precommit(self, context):
self._call_on_drivers("update_contract_precommit", context) self._call_on_drivers("update_policy_rule_set_precommit", context)
def update_contract_postcommit(self, context): def update_policy_rule_set_postcommit(self, context):
self._call_on_drivers("update_contract_postcommit", context) self._call_on_drivers("update_policy_rule_set_postcommit", context)
def delete_contract_precommit(self, context): def delete_policy_rule_set_precommit(self, context):
self._call_on_drivers("delete_contract_precommit", context) self._call_on_drivers("delete_policy_rule_set_precommit", context)
def delete_contract_postcommit(self, context): def delete_policy_rule_set_postcommit(self, context):
self._call_on_drivers("delete_contract_postcommit", context, self._call_on_drivers("delete_policy_rule_set_postcommit", context,
continue_on_failure=True) continue_on_failure=True)

View File

@ -44,12 +44,12 @@ class PendingServiceChainInsertions(object):
"""Encapsulates a ServiceChain Insertion Operation""" """Encapsulates a ServiceChain Insertion Operation"""
def __init__(self, context, node_stacks, chain_instance_id, def __init__(self, context, node_stacks, chain_instance_id,
provider_epg, consumer_epg, classifier): provider_ptg, consumer_ptg, classifier):
self.context = context self.context = context
self.node_stacks = node_stacks self.node_stacks = node_stacks
self.chain_instance_id = chain_instance_id self.chain_instance_id = chain_instance_id
self.provider_epg = provider_epg self.provider_ptg = provider_ptg
self.consumer_epg = consumer_epg self.consumer_ptg = consumer_ptg
self.classifier = classifier self.classifier = classifier
@ -88,8 +88,8 @@ class OneconvergenceServiceChainDriver(simplechain_driver.SimpleChainDriver):
thread_context, thread_context,
node_stacks, node_stacks,
context.current['id'], context.current['id'],
context.current['provider_epg'], context.current['provider_ptg'],
context.current['consumer_epg'], context.current['consumer_ptg'],
context.current['classifier']) context.current['classifier'])
eventlet.spawn_n(self._process_chain_processing, pendinginsertion) eventlet.spawn_n(self._process_chain_processing, pendinginsertion)
@ -127,8 +127,8 @@ class OneconvergenceServiceChainDriver(simplechain_driver.SimpleChainDriver):
thread_context, thread_context,
node_stacks, node_stacks,
context.current['id'], context.current['id'],
context.current['provider_epg'], context.current['provider_ptg'],
context.current['consumer_epg'], context.current['consumer_ptg'],
context.current['classifier']) context.current['classifier'])
eventlet.spawn_n(self._process_chain_processing, pendinginsertion) eventlet.spawn_n(self._process_chain_processing, pendinginsertion)
@ -286,8 +286,8 @@ class OneconvergenceServiceChainDriver(simplechain_driver.SimpleChainDriver):
nvsd_action_list = self._create_nvsd_services_action(context, nvsd_action_list = self._create_nvsd_services_action(context,
service_ids) service_ids)
left_group = pending_chain.consumer_epg left_group = pending_chain.consumer_ptg
right_group = pending_chain.provider_epg right_group = pending_chain.provider_ptg
classifier_id = pending_chain.classifier classifier_id = pending_chain.classifier
if nvsd_action_list: if nvsd_action_list:
policy_id = self.create_nvsd_policy(context, left_group, policy_id = self.create_nvsd_policy(context, left_group,

View File

@ -84,7 +84,7 @@ class SimpleChainDriver(object):
def update_servicechain_spec_postcommit(self, context): def update_servicechain_spec_postcommit(self, context):
filters = {'servicechain_spec': [context.original['id']]} filters = {'servicechain_spec': [context.original['id']]}
sc_instances = context._plugin.get_servicechain_instances( sc_instances = context._plugin.get_servicechain_instances(
context._plugin_context, filters) context._plugin_context, filters)
if sc_instances: if sc_instances:
self._update_servicechain_instance(context, self._update_servicechain_instance(context,
sc_instances[0], sc_instances[0],
@ -122,7 +122,7 @@ class SimpleChainDriver(object):
new_spec_id = context.current.get('servicechain_spec') new_spec_id = context.current.get('servicechain_spec')
if original_spec_id != new_spec_id: if original_spec_id != new_spec_id:
newspec = context._plugin.get_servicechain_spec( newspec = context._plugin.get_servicechain_spec(
context._plugin_context, new_spec_id) context._plugin_context, new_spec_id)
self._update_servicechain_instance(context, context.current, self._update_servicechain_instance(context, context.current,
newspec) newspec)
@ -135,17 +135,17 @@ class SimpleChainDriver(object):
self._delete_servicechain_instance_stacks(context._plugin_context, self._delete_servicechain_instance_stacks(context._plugin_context,
context.current['id']) context.current['id'])
def _get_epg(self, context, epg_id): def _get_ptg(self, context, ptg_id):
return self._get_resource(self._grouppolicy_plugin, return self._get_resource(self._grouppolicy_plugin,
context._plugin_context, context._plugin_context,
'endpoint_group', 'policy_target_group',
epg_id) ptg_id)
def _get_ep(self, context, ep_id): def _get_pt(self, context, pt_id):
return self._get_resource(self._grouppolicy_plugin, return self._get_resource(self._grouppolicy_plugin,
context._plugin_context, context._plugin_context,
'endpoint', 'policy_target',
ep_id) pt_id)
def _get_port(self, context, port_id): def _get_port(self, context, port_id):
return self._get_resource(self._core_plugin, return self._get_resource(self._core_plugin,
@ -153,17 +153,17 @@ class SimpleChainDriver(object):
'port', 'port',
port_id) port_id)
def _get_epg_subnet(self, context, epg_id): def _get_ptg_subnet(self, context, ptg_id):
epg = self._get_epg(context, epg_id) ptg = self._get_ptg(context, ptg_id)
return epg.get("subnets")[0] return ptg.get("subnets")[0]
def _get_member_ips(self, context, epg_id): def _get_member_ips(self, context, ptg_id):
epg = self._get_epg(context, epg_id) ptg = self._get_ptg(context, ptg_id)
ep_ids = epg.get("endpoints") pt_ids = ptg.get("policy_targets")
member_addresses = [] member_addresses = []
for ep_id in ep_ids: for pt_id in pt_ids:
ep = self._get_ep(context, ep_id) pt = self._get_pt(context, pt_id)
port_id = ep.get("port_id") port_id = pt.get("port_id")
port = self._get_port(context, port_id) port = self._get_port(context, port_id)
ipAddress = port.get('fixed_ips')[0].get("ip_address") ipAddress = port.get('fixed_ips')[0].get("ip_address")
member_addresses.append(ipAddress) member_addresses.append(ipAddress)
@ -172,7 +172,7 @@ class SimpleChainDriver(object):
def _fetch_template_and_params(self, context, sc_instance, def _fetch_template_and_params(self, context, sc_instance,
sc_spec, sc_node): sc_spec, sc_node):
stack_template = sc_node.get('config') stack_template = sc_node.get('config')
#TODO(magesh):Raise an exception ?? # TODO(magesh):Raise an exception ??
if not stack_template: if not stack_template:
LOG.error(_("Service Config is not defined for the service" LOG.error(_("Service Config is not defined for the service"
" chain Node")) " chain Node"))
@ -180,33 +180,33 @@ class SimpleChainDriver(object):
stack_template = jsonutils.loads(stack_template) stack_template = jsonutils.loads(stack_template)
config_param_values = sc_instance.get('config_param_values', {}) config_param_values = sc_instance.get('config_param_values', {})
stack_params = {} stack_params = {}
#config_param_values has the parameters for all Nodes. Only apply # config_param_values has the parameters for all Nodes. Only apply
#the ones relevant for this Node # the ones relevant for this Node
if config_param_values: if config_param_values:
config_param_values = jsonutils.loads(config_param_values) config_param_values = jsonutils.loads(config_param_values)
config_param_names = sc_spec.get('config_param_names', []) config_param_names = sc_spec.get('config_param_names', [])
if config_param_names: if config_param_names:
config_param_names = ast.literal_eval(config_param_names) config_param_names = ast.literal_eval(config_param_names)
#This service chain driver knows how to fill in two parameter values # This service chain driver knows how to fill in two parameter values
#for the template at present. # for the template at present.
#1)Subnet -> Provider EPG subnet is used # 1)Subnet -> Provider PTG subnet is used
#2)PoolMemberIPs -> List of IP Addresses of all EPs in Provider EPG # 2)PoolMemberIPs -> List of IP Addresses of all PTs in Provider PTG
#TODO(magesh):Process on the basis of ResourceType rather than Name # TODO(magesh):Process on the basis of ResourceType rather than Name
#eg: Type: OS::Neutron::PoolMember # eg: Type: OS::Neutron::PoolMember
#Variable number of pool members is not handled yet. We may have to # Variable number of pool members is not handled yet. We may have to
#dynamically modify the template json to achieve that # dynamically modify the template json to achieve that
provider_epg = sc_instance.get("provider_epg") provider_ptg = sc_instance.get("provider_ptg")
for key in config_param_names or []: for key in config_param_names or []:
if key == "PoolMemberIPs": if key == "PoolMemberIPs":
value = self._get_member_ips(context, provider_epg) value = self._get_member_ips(context, provider_ptg)
#TODO(Magesh):Return one value for now # TODO(Magesh):Return one value for now
if value: if value:
value = value[0] value = value[0]
config_param_values[key] = value config_param_values[key] = value
elif key == "Subnet": elif key == "Subnet":
value = self._get_epg_subnet(context, provider_epg) value = self._get_ptg_subnet(context, provider_ptg)
config_param_values[key] = value config_param_values[key] = value
node_params = (stack_template.get('Parameters') node_params = (stack_template.get('Parameters')
or stack_template.get('parameters')) or stack_template.get('parameters'))
@ -224,7 +224,7 @@ class SimpleChainDriver(object):
context._plugin_context, sc_node_id) context._plugin_context, sc_node_id)
stack_template, stack_params = self._fetch_template_and_params( stack_template, stack_params = self._fetch_template_and_params(
context, sc_instance, sc_spec, sc_node) context, sc_instance, sc_spec, sc_node)
stack = heatclient.create( stack = heatclient.create(
"stack_" + sc_instance['name'] + sc_node['name'] "stack_" + sc_instance['name'] + sc_node['name']
@ -232,8 +232,9 @@ class SimpleChainDriver(object):
stack_template, stack_template,
stack_params) stack_params)
self._insert_chain_stack_db(context._plugin_context.session, self._insert_chain_stack_db(
sc_instance['id'], stack['stack']['id']) context._plugin_context.session, sc_instance['id'],
stack['stack']['id'])
def _delete_servicechain_instance_stacks(self, context, instance_id): def _delete_servicechain_instance_stacks(self, context, instance_id):
stack_ids = self._get_chain_stacks(context.session, instance_id) stack_ids = self._get_chain_stacks(context.session, instance_id)
@ -245,7 +246,7 @@ class SimpleChainDriver(object):
def _get_instance_by_spec_id(self, context, spec_id): def _get_instance_by_spec_id(self, context, spec_id):
filters = {'servicechain_spec': [spec_id]} filters = {'servicechain_spec': [spec_id]}
return context._plugin.get_servicechain_instances( return context._plugin.get_servicechain_instances(
context._plugin_context, filters) context._plugin_context, filters)
def _update_servicechain_instance(self, context, sc_instance, newspec): def _update_servicechain_instance(self, context, sc_instance, newspec):
self._delete_servicechain_instance_stacks(context._plugin_context, self._delete_servicechain_instance_stacks(context._plugin_context,

View File

@ -58,28 +58,28 @@ class GroupPolicyDBTestBase(object):
self.assertEqual(sorted([i['id'] for i in res[resource_plural]]), self.assertEqual(sorted([i['id'] for i in res[resource_plural]]),
sorted([i[resource]['id'] for i in items])) sorted([i[resource]['id'] for i in items]))
def _get_test_endpoint_attrs(self, name='ep1', description='test ep', def _get_test_policy_target_attrs(
endpoint_group_id=None): self, name='pt1', description='test pt', policy_target_group_id=None):
attrs = {'name': name, 'description': description, attrs = {'name': name, 'description': description,
'endpoint_group_id': endpoint_group_id, 'policy_target_group_id': policy_target_group_id,
'tenant_id': self._tenant_id} 'tenant_id': self._tenant_id}
return attrs return attrs
def _get_test_endpoint_group_attrs(self, name='epg1', def _get_test_policy_target_group_attrs(self, name='ptg1',
description='test epg', description='test ptg',
l2_policy_id=None, l2_policy_id=None,
provided_contracts=None, provided_policy_rule_sets=None,
consumed_contracts=None): consumed_policy_rule_sets=None):
pc_ids = cc_ids = [] pprs_ids = cprs_ids = []
if provided_contracts: if provided_policy_rule_sets:
pc_ids = [pc_id for pc_id in provided_contracts] pprs_ids = [pprs_id for pprs_id in provided_policy_rule_sets]
if consumed_contracts: if consumed_policy_rule_sets:
cc_ids = [cc_id for cc_id in consumed_contracts] cprs_ids = [cc_id for cc_id in consumed_policy_rule_sets]
attrs = {'name': name, 'description': description, attrs = {'name': name, 'description': description,
'tenant_id': self._tenant_id, 'l2_policy_id': l2_policy_id, 'tenant_id': self._tenant_id, 'l2_policy_id': l2_policy_id,
'provided_contracts': pc_ids, 'provided_policy_rule_sets': pprs_ids,
'consumed_contracts': cc_ids} 'consumed_policy_rule_sets': cprs_ids}
return attrs return attrs
@ -145,63 +145,66 @@ class GroupPolicyDBTestBase(object):
return attrs return attrs
def _get_test_contract_attrs(self, name='contract1', def _get_test_prs_attrs(self, name='policy_rule_set1',
description='test contract', description='test policy_rule_set',
child_contracts=None, policy_rules=None): child_policy_rule_sets=None,
if not child_contracts: policy_rules=None):
child_contracts = [] if not child_policy_rule_sets:
child_policy_rule_sets = []
if not policy_rules: if not policy_rules:
policy_rules = [] policy_rules = []
attrs = {'name': name, 'description': description, attrs = {'name': name, 'description': description,
'tenant_id': self._tenant_id, 'tenant_id': self._tenant_id,
'child_contracts': child_contracts, 'child_policy_rule_sets': child_policy_rule_sets,
'policy_rules': policy_rules} 'policy_rules': policy_rules}
return attrs return attrs
def create_endpoint(self, endpoint_group_id=None, def create_policy_target(self, policy_target_group_id=None,
expected_res_status=None, **kwargs): expected_res_status=None, **kwargs):
defaults = {'name': 'ep1', 'description': 'test ep'} defaults = {'name': 'pt1', 'description': 'test pt'}
defaults.update(kwargs) defaults.update(kwargs)
data = {'endpoint': {'endpoint_group_id': endpoint_group_id, data = {'policy_target':
'tenant_id': self._tenant_id}} {'policy_target_group_id': policy_target_group_id,
data['endpoint'].update(defaults) 'tenant_id': self._tenant_id}}
data['policy_target'].update(defaults)
ep_req = self.new_create_request('endpoints', data, self.fmt) pt_req = self.new_create_request('policy_targets', data, self.fmt)
ep_res = ep_req.get_response(self.ext_api) pt_res = pt_req.get_response(self.ext_api)
if expected_res_status: if expected_res_status:
self.assertEqual(ep_res.status_int, expected_res_status) self.assertEqual(pt_res.status_int, expected_res_status)
elif ep_res.status_int >= webob.exc.HTTPClientError.code: elif pt_res.status_int >= webob.exc.HTTPClientError.code:
raise webob.exc.HTTPClientError(code=ep_res.status_int) raise webob.exc.HTTPClientError(code=pt_res.status_int)
ep = self.deserialize(self.fmt, ep_res) pt = self.deserialize(self.fmt, pt_res)
return ep return pt
def create_endpoint_group(self, l2_policy_id=None, def create_policy_target_group(self, l2_policy_id=None,
expected_res_status=None, **kwargs): expected_res_status=None, **kwargs):
defaults = {'name': 'epg1', 'description': 'test epg', defaults = {'name': 'ptg1', 'description': 'test ptg',
'provided_contracts': {}, 'provided_policy_rule_sets': {},
'consumed_contracts': {}} 'consumed_policy_rule_sets': {}}
defaults.update(kwargs) defaults.update(kwargs)
data = {'endpoint_group': {'tenant_id': self._tenant_id, data = {'policy_target_group': {'tenant_id': self._tenant_id,
'l2_policy_id': l2_policy_id}} 'l2_policy_id': l2_policy_id}}
data['endpoint_group'].update(defaults) data['policy_target_group'].update(defaults)
epg_req = self.new_create_request('endpoint_groups', data, self.fmt) ptg_req = self.new_create_request(
epg_res = epg_req.get_response(self.ext_api) 'policy_target_groups', data, self.fmt)
ptg_res = ptg_req.get_response(self.ext_api)
if expected_res_status: if expected_res_status:
self.assertEqual(epg_res.status_int, expected_res_status) self.assertEqual(ptg_res.status_int, expected_res_status)
elif epg_res.status_int >= webob.exc.HTTPClientError.code: elif ptg_res.status_int >= webob.exc.HTTPClientError.code:
raise webob.exc.HTTPClientError(code=epg_res.status_int) raise webob.exc.HTTPClientError(code=ptg_res.status_int)
epg = self.deserialize(self.fmt, epg_res) ptg = self.deserialize(self.fmt, ptg_res)
return epg return ptg
def create_l2_policy(self, l3_policy_id=None, expected_res_status=None, def create_l2_policy(self, l3_policy_id=None, expected_res_status=None,
**kwargs): **kwargs):
@ -333,26 +336,27 @@ class GroupPolicyDBTestBase(object):
return pr return pr
def create_contract(self, expected_res_status=None, **kwargs): def create_policy_rule_set(self, expected_res_status=None, **kwargs):
defaults = {'name': 'contract1', 'description': 'test contract', defaults = {'name': 'policy_rule_set1',
'child_contracts': [], 'policy_rules': []} 'description': 'test policy_rule_set',
'child_policy_rule_sets': [], 'policy_rules': []}
defaults.update(kwargs) defaults.update(kwargs)
kwargs = defaults kwargs = defaults
data = {'contract': {'tenant_id': self._tenant_id}} data = {'policy_rule_set': {'tenant_id': self._tenant_id}}
data['contract'].update(kwargs) data['policy_rule_set'].update(kwargs)
ct_req = self.new_create_request('contracts', data, self.fmt) prs_req = self.new_create_request('policy_rule_sets', data, self.fmt)
ct_res = ct_req.get_response(self.ext_api) prs_res = prs_req.get_response(self.ext_api)
if expected_res_status: if expected_res_status:
self.assertEqual(ct_res.status_int, expected_res_status) self.assertEqual(prs_res.status_int, expected_res_status)
elif ct_res.status_int >= webob.exc.HTTPClientError.code: elif prs_res.status_int >= webob.exc.HTTPClientError.code:
raise webob.exc.HTTPClientError(code=ct_res.status_int) raise webob.exc.HTTPClientError(code=prs_res.status_int)
ct = self.deserialize(self.fmt, ct_res) prs = self.deserialize(self.fmt, prs_res)
return ct return prs
class GroupPolicyDBTestPlugin(gpdb.GroupPolicyDbPlugin): class GroupPolicyDBTestPlugin(gpdb.GroupPolicyDbPlugin):
@ -398,137 +402,147 @@ class TestGroupResources(GroupPolicyDbTestCase):
for k, v in attrs.iteritems(): for k, v in attrs.iteritems():
self.assertEqual(res[resource][k], v) self.assertEqual(res[resource][k], v)
def test_create_and_show_endpoint(self): def test_create_and_show_policy_target(self):
epg_id = self.create_endpoint_group()['endpoint_group']['id'] ptg_id = self.create_policy_target_group()['policy_target_group']['id']
attrs = self._get_test_endpoint_attrs(endpoint_group_id=epg_id) attrs = self._get_test_policy_target_attrs(
policy_target_group_id=ptg_id)
ep = self.create_endpoint(endpoint_group_id=epg_id) pt = self.create_policy_target(policy_target_group_id=ptg_id)
for k, v in attrs.iteritems(): for k, v in attrs.iteritems():
self.assertEqual(ep['endpoint'][k], v) self.assertEqual(pt['policy_target'][k], v)
req = self.new_show_request('endpoint_groups', epg_id, fmt=self.fmt) req = self.new_show_request(
'policy_target_groups', ptg_id, fmt=self.fmt)
res = self.deserialize(self.fmt, req.get_response(self.ext_api)) res = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(res['endpoint_group']['endpoints'], self.assertEqual(res['policy_target_group']['policy_targets'],
[ep['endpoint']['id']]) [pt['policy_target']['id']])
self._test_show_resource('endpoint', ep['endpoint']['id'], attrs) self._test_show_resource(
'policy_target', pt['policy_target']['id'], attrs)
def test_list_endpoints(self): def test_list_policy_targets(self):
eps = [self.create_endpoint(name='ep1', description='ep'), pts = [self.create_policy_target(name='pt1', description='pt'),
self.create_endpoint(name='ep2', description='ep'), self.create_policy_target(name='pt2', description='pt'),
self.create_endpoint(name='ep3', description='ep')] self.create_policy_target(name='pt3', description='pt')]
self._test_list_resources('endpoint', eps, self._test_list_resources('policy_target', pts,
query_params='description=ep') query_params='description=pt')
def test_update_endpoint(self): def test_update_policy_target(self):
name = 'new_endpoint' name = 'new_policy_target'
description = 'new desc' description = 'new desc'
attrs = self._get_test_endpoint_attrs(name=name, attrs = self._get_test_policy_target_attrs(name=name,
description=description) description=description)
ep = self.create_endpoint() pt = self.create_policy_target()
data = {'endpoint': {'name': name, 'description': description}} data = {'policy_target': {'name': name, 'description': description}}
req = self.new_update_request('endpoints', data, ep['endpoint']['id']) req = self.new_update_request(
'policy_targets', data, pt['policy_target']['id'])
res = self.deserialize(self.fmt, req.get_response(self.ext_api)) res = self.deserialize(self.fmt, req.get_response(self.ext_api))
for k, v in attrs.iteritems(): for k, v in attrs.iteritems():
self.assertEqual(res['endpoint'][k], v) self.assertEqual(res['policy_target'][k], v)
self._test_show_resource('endpoint', ep['endpoint']['id'], attrs) self._test_show_resource(
'policy_target', pt['policy_target']['id'], attrs)
def test_delete_endpoint(self): def test_delete_policy_target(self):
ctx = context.get_admin_context() ctx = context.get_admin_context()
ep = self.create_endpoint() pt = self.create_policy_target()
ep_id = ep['endpoint']['id'] pt_id = pt['policy_target']['id']
req = self.new_delete_request('endpoints', ep_id) req = self.new_delete_request('policy_targets', pt_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
self.assertRaises(gpolicy.EndpointNotFound, self.plugin.get_endpoint, self.assertRaises(gpolicy.PolicyTargetNotFound,
ctx, ep_id) self.plugin.get_policy_target, ctx, pt_id)
def test_create_and_show_endpoint_group(self): def test_create_and_show_policy_target_group(self):
name = "epg1" name = "ptg1"
l3p = self.create_l3_policy() l3p = self.create_l3_policy()
l3p_id = l3p['l3_policy']['id'] l3p_id = l3p['l3_policy']['id']
l2p = self.create_l2_policy(name=name, l3_policy_id=l3p_id) l2p = self.create_l2_policy(name=name, l3_policy_id=l3p_id)
l2p_id = l2p['l2_policy']['id'] l2p_id = l2p['l2_policy']['id']
provided_ct_id = self.create_contract()['contract']['id'] provided_prs_id = (
consumed_ct_id = self.create_contract()['contract']['id'] self.create_policy_rule_set()['policy_rule_set']['id'])
attrs = self._get_test_endpoint_group_attrs(name, consumed_prs_id = (
l2_policy_id=l2p_id, self.create_policy_rule_set()['policy_rule_set']['id'])
provided_contracts= attrs = self._get_test_policy_target_group_attrs(
[provided_ct_id], name, l2_policy_id=l2p_id,
consumed_contracts= provided_policy_rule_sets=[provided_prs_id],
[consumed_ct_id]) consumed_policy_rule_sets=[consumed_prs_id])
epg = self.create_endpoint_group(name=name, l2_policy_id=l2p_id, ptg = self.create_policy_target_group(
provided_contracts={provided_ct_id: name=name, l2_policy_id=l2p_id,
None}, provided_policy_rule_sets={provided_prs_id: None},
consumed_contracts={consumed_ct_id: consumed_policy_rule_sets={consumed_prs_id: None})
None})
for k, v in attrs.iteritems(): for k, v in attrs.iteritems():
self.assertEqual(epg['endpoint_group'][k], v) self.assertEqual(ptg['policy_target_group'][k], v)
self._test_show_resource('endpoint_group', epg['endpoint_group']['id'], self._test_show_resource(
attrs) 'policy_target_group', ptg['policy_target_group']['id'], attrs)
def test_list_endpoint_groups(self): def test_list_policy_target_groups(self):
epgs = [self.create_endpoint_group(name='epg1', description='epg'), ptgs = (
self.create_endpoint_group(name='epg2', description='epg'), [self.create_policy_target_group(name='ptg1', description='ptg'),
self.create_endpoint_group(name='epg3', description='epg')] self.create_policy_target_group(name='ptg2', description='ptg'),
self._test_list_resources('endpoint_group', epgs, self.create_policy_target_group(name='ptg3', description='ptg')])
query_params='description=epg') self._test_list_resources('policy_target_group', ptgs,
query_params='description=ptg')
def test_update_endpoint_group(self): def test_update_policy_target_group(self):
name = "new_endpoint_group1" name = "new_policy_target_group1"
description = 'new desc' description = 'new desc'
l3p_id = self.create_l3_policy()['l3_policy']['id'] l3p_id = self.create_l3_policy()['l3_policy']['id']
l2p_id = self.create_l2_policy(l3_policy_id=l3p_id)['l2_policy']['id'] l2p_id = self.create_l2_policy(l3_policy_id=l3p_id)['l2_policy']['id']
attrs = self._get_test_endpoint_group_attrs(name=name, attrs = self._get_test_policy_target_group_attrs(
description=description, name=name, description=description, l2_policy_id=l2p_id)
l2_policy_id=l2p_id) ct1_id = self.create_policy_rule_set(
ct1_id = self.create_contract(name='contract1')['contract']['id'] name='policy_rule_set1')['policy_rule_set']['id']
ct2_id = self.create_contract(name='contract2')['contract']['id'] ct2_id = self.create_policy_rule_set(
epg = self.create_endpoint_group(consumed_contracts={ct1_id: 'scope'}, name='policy_rule_set2')['policy_rule_set']['id']
provided_contracts={ct2_id: 'scope'}) ptg = self.create_policy_target_group(
ct3_id = self.create_contract(name='contract3')['contract']['id'] consumed_policy_rule_sets={ct1_id: 'scope'},
ct4_id = self.create_contract(name='contract4')['contract']['id'] provided_policy_rule_sets={ct2_id: 'scope'})
data = {'endpoint_group': {'name': name, 'description': description, ct3_id = self.create_policy_rule_set(
'l2_policy_id': l2p_id, name='policy_rule_set3')['policy_rule_set']['id']
'provided_contracts': {ct3_id: 'scope'}, ct4_id = self.create_policy_rule_set(
'consumed_contracts': {ct4_id: 'scope'}}} name='policy_rule_set4')['policy_rule_set']['id']
req = self.new_update_request('endpoint_groups', data, data = {'policy_target_group':
epg['endpoint_group']['id']) {'name': name, 'description': description,
'l2_policy_id': l2p_id,
'provided_policy_rule_sets': {ct3_id: 'scope'},
'consumed_policy_rule_sets': {ct4_id: 'scope'}}}
req = self.new_update_request('policy_target_groups', data,
ptg['policy_target_group']['id'])
res = self.deserialize(self.fmt, req.get_response(self.ext_api)) res = self.deserialize(self.fmt, req.get_response(self.ext_api))
attrs['provided_contracts'] = [ct3_id] attrs['provided_policy_rule_sets'] = [ct3_id]
attrs['consumed_contracts'] = [ct4_id] attrs['consumed_policy_rule_sets'] = [ct4_id]
for k, v in attrs.iteritems(): for k, v in attrs.iteritems():
self.assertEqual(res['endpoint_group'][k], v) self.assertEqual(res['policy_target_group'][k], v)
self._test_show_resource('endpoint_group', self._test_show_resource('policy_target_group',
epg['endpoint_group']['id'], attrs) ptg['policy_target_group']['id'], attrs)
def test_delete_endpoint_group(self): def test_delete_policy_target_group(self):
ctx = context.get_admin_context() ctx = context.get_admin_context()
epg = self.create_endpoint_group() ptg = self.create_policy_target_group()
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
req = self.new_delete_request('endpoint_groups', epg_id) req = self.new_delete_request('policy_target_groups', ptg_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
self.assertRaises(gpolicy.EndpointGroupNotFound, self.assertRaises(gpolicy.PolicyTargetGroupNotFound,
self.plugin.get_endpoint_group, ctx, epg_id) self.plugin.get_policy_target_group, ctx, ptg_id)
def test_create_and_show_l2_policy(self): def test_create_and_show_l2_policy(self):
l3p_id = self.create_l3_policy()['l3_policy']['id'] l3p_id = self.create_l3_policy()['l3_policy']['id']
@ -920,26 +934,26 @@ class TestGroupResources(GroupPolicyDbTestCase):
self.assertRaises(gpolicy.PolicyRuleNotFound, self.assertRaises(gpolicy.PolicyRuleNotFound,
self.plugin.get_policy_rule, ctx, pr_id) self.plugin.get_policy_rule, ctx, pr_id)
def test_create_and_show_contract(self): def test_create_and_show_policy_rule_set(self):
name = "contract1" name = "policy_rule_set1"
attrs = self._get_test_contract_attrs(name=name) attrs = self._get_test_prs_attrs(name=name)
ct = self.create_contract(name=name) prs = self.create_policy_rule_set(name=name)
for k, v in attrs.iteritems(): for k, v in attrs.iteritems():
self.assertEqual(ct['contract'][k], v) self.assertEqual(prs['policy_rule_set'][k], v)
req = self.new_show_request('contracts', ct['contract']['id'], req = self.new_show_request(
fmt=self.fmt) 'policy_rule_sets', prs['policy_rule_set']['id'], fmt=self.fmt)
res = self.deserialize(self.fmt, req.get_response(self.ext_api)) res = self.deserialize(self.fmt, req.get_response(self.ext_api))
for k, v in attrs.iteritems(): for k, v in attrs.iteritems():
self.assertEqual(res['contract'][k], v) self.assertEqual(res['policy_rule_set'][k], v)
self._test_show_resource('contract', self._test_show_resource('policy_rule_set',
ct['contract']['id'], attrs) prs['policy_rule_set']['id'], attrs)
def test_create_contract_with_multiple_rules_children(self, **kwargs): def test_create_prs_with_multiple_rules_children(self, **kwargs):
policy_classifiers = [ policy_classifiers = [
self.create_policy_classifier()['policy_classifier']['id'], self.create_policy_classifier()['policy_classifier']['id'],
self.create_policy_classifier()['policy_classifier']['id']] self.create_policy_classifier()['policy_classifier']['id']]
@ -950,109 +964,119 @@ class TestGroupResources(GroupPolicyDbTestCase):
self.create_policy_rule( self.create_policy_rule(
policy_classifier_id= policy_classifier_id=
policy_classifiers[1])['policy_rule']['id']]) policy_classifiers[1])['policy_rule']['id']])
child_contracts = sorted([self.create_contract()['contract']['id'], child_policy_rule_sets = sorted(
self.create_contract()['contract']['id']]) [self.create_policy_rule_set()['policy_rule_set']['id'],
attrs = self._get_test_contract_attrs( self.create_policy_rule_set()['policy_rule_set']['id']])
policy_rules=policy_rules, child_contracts=child_contracts) attrs = self._get_test_prs_attrs(
ct = self.create_contract(policy_rules=policy_rules, policy_rules=policy_rules,
child_contracts=child_contracts) child_policy_rule_sets=child_policy_rule_sets)
prs = self.create_policy_rule_set(
policy_rules=policy_rules,
child_policy_rule_sets=child_policy_rule_sets)
req = self.new_show_request('contracts', ct['contract']['id'], req = self.new_show_request('policy_rule_sets',
prs['policy_rule_set']['id'],
fmt=self.fmt) fmt=self.fmt)
res = self.deserialize(self.fmt, req.get_response(self.ext_api)) res = self.deserialize(self.fmt, req.get_response(self.ext_api))
parent_id = res['contract']['id'] parent_id = res['policy_rule_set']['id']
res['contract']['policy_rules'] = sorted( res['policy_rule_set']['policy_rules'] = sorted(
res['contract']['policy_rules']) res['policy_rule_set']['policy_rules'])
res['contract']['child_contracts'] = sorted( res['policy_rule_set']['child_policy_rule_sets'] = sorted(
res['contract']['child_contracts']) res['policy_rule_set']['child_policy_rule_sets'])
for k, v in attrs.iteritems(): for k, v in attrs.iteritems():
self.assertEqual(res['contract'][k], v) self.assertEqual(res['policy_rule_set'][k], v)
req = self.new_show_request('contracts', child_contracts[0], req = self.new_show_request('policy_rule_sets',
child_policy_rule_sets[0],
fmt=self.fmt) fmt=self.fmt)
c1 = self.deserialize(self.fmt, req.get_response(self.ext_api)) c1 = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(c1['contract']['parent_id'], parent_id) self.assertEqual(c1['policy_rule_set']['parent_id'], parent_id)
req = self.new_show_request('contracts', child_contracts[1], req = self.new_show_request('policy_rule_sets',
child_policy_rule_sets[1],
fmt=self.fmt) fmt=self.fmt)
c2 = self.deserialize(self.fmt, req.get_response(self.ext_api)) c2 = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(c2['contract']['parent_id'], parent_id) self.assertEqual(c2['policy_rule_set']['parent_id'], parent_id)
def test_create_child_contract_fail(self, **kwargs): def test_create_child_prs_fail(self, **kwargs):
self.create_contract(child_contracts=[ self.create_policy_rule_set(child_policy_rule_sets=[
'00000000-ffff-ffff-ffff-000000000000'], '00000000-ffff-ffff-ffff-000000000000'],
expected_res_status=webob.exc.HTTPNotFound.code) expected_res_status=webob.exc.HTTPNotFound.code)
def test_list_contracts(self): def test_list_policy_rule_sets(self):
contracts = [ policy_rule_sets = [
self.create_contract(name='ct1', description='ct'), self.create_policy_rule_set(name='ct1', description='ct'),
self.create_contract(name='ct2', description='ct'), self.create_policy_rule_set(name='ct2', description='ct'),
self.create_contract(name='ct3', description='ct')] self.create_policy_rule_set(name='ct3', description='ct')]
self._test_list_resources('contract', contracts, self._test_list_resources('policy_rule_set', policy_rule_sets,
query_params='description=ct') query_params='description=ct')
def test_update_contract(self): def test_update_policy_rule_set(self):
name = "new_contract" name = "new_policy_rule_set"
description = 'new desc' description = 'new desc'
pc_id = self.create_policy_classifier()['policy_classifier']['id'] pc_id = self.create_policy_classifier()['policy_classifier']['id']
policy_rules = [self.create_policy_rule( policy_rules = [self.create_policy_rule(
policy_classifier_id=pc_id)['policy_rule']['id']] policy_classifier_id=pc_id)['policy_rule']['id']]
child_contracts = [self.create_contract()['contract']['id']] child_policy_rule_sets = [
ct = self.create_contract(child_contracts=child_contracts, self.create_policy_rule_set()['policy_rule_set']['id']]
policy_rules=policy_rules) prs = self.create_policy_rule_set(
child_contracts = [self.create_contract()['contract']['id']] child_policy_rule_sets=child_policy_rule_sets,
policy_rules=policy_rules)
child_policy_rule_sets = [
self.create_policy_rule_set()['policy_rule_set']['id']]
policy_rules = [self.create_policy_rule( policy_rules = [self.create_policy_rule(
policy_classifier_id=pc_id)['policy_rule']['id']] policy_classifier_id=pc_id)['policy_rule']['id']]
attrs = self._get_test_contract_attrs( attrs = self._get_test_prs_attrs(
name=name, description=description, policy_rules=policy_rules, name=name, description=description, policy_rules=policy_rules,
child_contracts=child_contracts) child_policy_rule_sets=child_policy_rule_sets)
data = {'contract': {'name': name, 'description': description, data = {'policy_rule_set':
'policy_rules': policy_rules, {'name': name, 'description': description,
'child_contracts': child_contracts}} 'policy_rules': policy_rules,
'child_policy_rule_sets': child_policy_rule_sets}}
req = self.new_update_request('contracts', data, req = self.new_update_request('policy_rule_sets', data,
ct['contract']['id']) prs['policy_rule_set']['id'])
res = self.deserialize(self.fmt, req.get_response(self.ext_api)) res = self.deserialize(self.fmt, req.get_response(self.ext_api))
for k, v in attrs.iteritems(): for k, v in attrs.iteritems():
self.assertEqual(res['contract'][k], v) self.assertEqual(res['policy_rule_set'][k], v)
self._test_show_resource('contract', self._test_show_resource('policy_rule_set',
ct['contract']['id'], attrs) prs['policy_rule_set']['id'], attrs)
def test_delete_contract(self): def test_delete_policy_rule_set(self):
ctx = context.get_admin_context() ctx = context.get_admin_context()
ct = self.create_contract() prs = self.create_policy_rule_set()
ct_id = ct['contract']['id'] prs_id = prs['policy_rule_set']['id']
req = self.new_delete_request('contracts', ct_id) req = self.new_delete_request('policy_rule_sets', prs_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
self.assertRaises(gpolicy.ContractNotFound, self.assertRaises(gpolicy.PolicyRuleSetNotFound,
self.plugin.get_contract, ctx, ct_id) self.plugin.get_policy_rule_set, ctx, prs_id)
def test_contract_one_hierarchy_children(self): def test_prs_one_hierarchy_children(self):
child = self.create_contract()['contract'] child = self.create_policy_rule_set()['policy_rule_set']
parent = self.create_contract( parent = self.create_policy_rule_set(
child_contracts = [child['id']])['contract'] child_policy_rule_sets=[child['id']])['policy_rule_set']
self.create_contract( self.create_policy_rule_set(
child_contracts = [parent['id']], child_policy_rule_sets=[parent['id']],
expected_res_status=webob.exc.HTTPBadRequest.code) expected_res_status=webob.exc.HTTPBadRequest.code)
def test_contract_one_hierarchy_parent(self): def test_prs_one_hierarchy_parent(self):
child = self.create_contract()['contract'] child = self.create_policy_rule_set()['policy_rule_set']
# parent # parent
self.create_contract( self.create_policy_rule_set(
child_contracts = [child['id']])['contract'] child_policy_rule_sets=[child['id']])['policy_rule_set']
nephew = self.create_contract()['contract'] nephew = self.create_policy_rule_set()['policy_rule_set']
data = {'contract': {'child_contracts': [nephew['id']]}} data = {'policy_rule_set': {'child_policy_rule_sets': [nephew['id']]}}
req = self.new_update_request('contracts', data, child['id']) req = self.new_update_request('policy_rule_sets', data, child['id'])
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPBadRequest.code) self.assertEqual(res.status_int, webob.exc.HTTPBadRequest.code)
def test_contract_parent_no_loop(self): def test_prs_parent_no_loop(self):
ct = self.create_contract()['contract'] prs = self.create_policy_rule_set()['policy_rule_set']
data = {'contract': {'child_contracts': [ct['id']]}} data = {'policy_rule_set': {'child_policy_rule_sets': [prs['id']]}}
req = self.new_update_request('contracts', data, ct['id']) req = self.new_update_request('policy_rule_sets', data, prs['id'])
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPBadRequest.code) self.assertEqual(res.status_int, webob.exc.HTTPBadRequest.code)

View File

@ -50,24 +50,26 @@ class GroupPolicyMappingDbTestCase(tgpdb.GroupPolicyDbTestCase,
service_plugins=service_plugins service_plugins=service_plugins
) )
def _get_test_endpoint_attrs(self, name='ep1', description='test ep', def _get_test_policy_target_attrs(self, name='pt1',
endpoint_group_id=None, port_id=None): description='test pt',
policy_target_group_id=None,
port_id=None):
attrs = (super(GroupPolicyMappingDbTestCase, self). attrs = (super(GroupPolicyMappingDbTestCase, self).
_get_test_endpoint_attrs(name, description, _get_test_policy_target_attrs(name, description,
endpoint_group_id)) policy_target_group_id))
attrs.update({'port_id': port_id}) attrs.update({'port_id': port_id})
return attrs return attrs
def _get_test_endpoint_group_attrs(self, name='epg1', def _get_test_policy_target_group_attrs(self, name='ptg1',
description='test epg', description='test ptg',
l2_policy_id=None, l2_policy_id=None,
provided_contracts=None, provided_policy_rule_sets=None,
consumed_contracts=None, subnets=None): consumed_policy_rule_sets=None,
subnets=None):
attrs = (super(GroupPolicyMappingDbTestCase, self). attrs = (super(GroupPolicyMappingDbTestCase, self).
_get_test_endpoint_group_attrs(name, description, _get_test_policy_target_group_attrs(
l2_policy_id, name, description, l2_policy_id,
provided_contracts, provided_policy_rule_sets, consumed_policy_rule_sets))
consumed_contracts))
attrs.update({'subnets': subnets or []}) attrs.update({'subnets': subnets or []})
return attrs return attrs
@ -97,62 +99,62 @@ class TestMappedGroupResources(GroupPolicyMappingDbTestCase,
class TestMappedGroupResourceAttrs(GroupPolicyMappingDbTestCase): class TestMappedGroupResourceAttrs(GroupPolicyMappingDbTestCase):
def test_create_delete_endpoint_with_port(self): def test_create_delete_policy_target_with_port(self):
with self.port() as port: with self.port() as port:
port_id = port['port']['id'] port_id = port['port']['id']
ep = self.create_endpoint(port_id=port_id) pt = self.create_policy_target(port_id=port_id)
ep_id = ep['endpoint']['id'] pt_id = pt['policy_target']['id']
self.assertEqual(port_id, ep['endpoint']['port_id']) self.assertEqual(port_id, pt['policy_target']['port_id'])
req = self.new_show_request('endpoints', ep_id, fmt=self.fmt) req = self.new_show_request('policy_targets', pt_id, fmt=self.fmt)
res = self.deserialize(self.fmt, req.get_response(self.ext_api)) res = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(port_id, res['endpoint']['port_id']) self.assertEqual(port_id, res['policy_target']['port_id'])
req = self.new_delete_request('endpoints', ep_id) req = self.new_delete_request('policy_targets', pt_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
def test_create_delete_endpoint_group_with_subnets(self): def test_create_delete_policy_target_group_with_subnets(self):
with contextlib.nested(self.subnet(cidr='10.10.1.0/24'), with contextlib.nested(self.subnet(cidr='10.10.1.0/24'),
self.subnet(cidr='10.10.2.0/24')) as ( self.subnet(cidr='10.10.2.0/24')) as (
subnet1, subnet2): subnet1, subnet2):
subnets = [subnet1['subnet']['id'], subnet2['subnet']['id']] subnets = [subnet1['subnet']['id'], subnet2['subnet']['id']]
epg = self.create_endpoint_group(subnets=subnets) ptg = self.create_policy_target_group(subnets=subnets)
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
self.assertEqual(sorted(subnets), self.assertEqual(sorted(subnets),
sorted(epg['endpoint_group']['subnets'])) sorted(ptg['policy_target_group']['subnets']))
req = self.new_show_request('endpoint_groups', epg_id, req = self.new_show_request('policy_target_groups', ptg_id,
fmt=self.fmt) fmt=self.fmt)
res = self.deserialize(self.fmt, req.get_response(self.ext_api)) res = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(sorted(subnets), self.assertEqual(sorted(subnets),
sorted(res['endpoint_group']['subnets'])) sorted(res['policy_target_group']['subnets']))
req = self.new_delete_request('endpoint_groups', epg_id) req = self.new_delete_request('policy_target_groups', ptg_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
def test_update_endpoint_group_subnets(self): def test_update_policy_target_group_subnets(self):
with contextlib.nested(self.subnet(cidr='10.10.1.0/24'), with contextlib.nested(self.subnet(cidr='10.10.1.0/24'),
self.subnet(cidr='10.10.2.0/24'), self.subnet(cidr='10.10.2.0/24'),
self.subnet(cidr='10.10.3.0/24')) as ( self.subnet(cidr='10.10.3.0/24')) as (
subnet1, subnet2, subnet3): subnet1, subnet2, subnet3):
orig_subnets = [subnet1['subnet']['id'], subnet2['subnet']['id']] orig_subnets = [subnet1['subnet']['id'], subnet2['subnet']['id']]
epg = self.create_endpoint_group(subnets=orig_subnets) ptg = self.create_policy_target_group(subnets=orig_subnets)
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
self.assertEqual(sorted(orig_subnets), self.assertEqual(sorted(orig_subnets),
sorted(epg['endpoint_group']['subnets'])) sorted(ptg['policy_target_group']['subnets']))
new_subnets = [subnet1['subnet']['id'], subnet3['subnet']['id']] new_subnets = [subnet1['subnet']['id'], subnet3['subnet']['id']]
data = {'endpoint_group': {'subnets': new_subnets}} data = {'policy_target_group': {'subnets': new_subnets}}
req = self.new_update_request('endpoint_groups', data, epg_id) req = self.new_update_request('policy_target_groups', data, ptg_id)
res = self.deserialize(self.fmt, req.get_response(self.ext_api)) res = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(sorted(new_subnets), self.assertEqual(sorted(new_subnets),
sorted(res['endpoint_group']['subnets'])) sorted(res['policy_target_group']['subnets']))
req = self.new_show_request('endpoint_groups', epg_id, req = self.new_show_request('policy_target_groups', ptg_id,
fmt=self.fmt) fmt=self.fmt)
res = self.deserialize(self.fmt, req.get_response(self.ext_api)) res = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(sorted(new_subnets), self.assertEqual(sorted(new_subnets),
sorted(res['endpoint_group']['subnets'])) sorted(res['policy_target_group']['subnets']))
# REVISIT(rkukura): Remove delete once subnet() context # REVISIT(rkukura): Remove delete once subnet() context
# manager is replaced with a function that does not delete # manager is replaced with a function that does not delete
# the resource(s) that are created. # the resource(s) that are created.
req = self.new_delete_request('endpoint_groups', epg_id) req = self.new_delete_request('policy_target_groups', ptg_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)

View File

@ -68,8 +68,8 @@ class ServiceChainDBTestBase(object):
return attrs return attrs
def _get_test_servicechain_spec_attrs(self, name='scs1', def _get_test_servicechain_spec_attrs(self, name='scs1',
description='test scs', description='test scs',
nodes=None): nodes=None):
node_ids = [] node_ids = []
if nodes: if nodes:
node_ids = [node_id for node_id in nodes] node_ids = [node_id for node_id in nodes]
@ -80,18 +80,18 @@ class ServiceChainDBTestBase(object):
return attrs return attrs
def _get_test_servicechain_instance_attrs(self, name='sci1', def _get_test_servicechain_instance_attrs(self, name='sci1',
description='test sci', description='test sci',
config_param_values="{}", config_param_values="{}",
servicechain_spec=None, servicechain_spec=None,
provider_epg=None, provider_ptg=None,
consumer_epg=None, consumer_ptg=None,
classifier=None): classifier=None):
attrs = {'name': name, 'description': description, attrs = {'name': name, 'description': description,
'tenant_id': self._tenant_id, 'tenant_id': self._tenant_id,
'config_param_values': config_param_values, 'config_param_values': config_param_values,
'servicechain_spec': servicechain_spec, 'servicechain_spec': servicechain_spec,
'provider_epg': provider_epg, 'provider_ptg': provider_ptg,
'consumer_epg': consumer_epg, 'consumer_ptg': consumer_ptg,
'classifier': classifier} 'classifier': classifier}
return attrs return attrs
@ -142,19 +142,19 @@ class ServiceChainDBTestBase(object):
def create_servicechain_instance(self, servicechain_spec=None, def create_servicechain_instance(self, servicechain_spec=None,
config_param_values="{}", config_param_values="{}",
provider_epg=None, provider_ptg=None,
consumer_epg=None, consumer_ptg=None,
classifier=None, classifier=None,
expected_res_status=None, **kwargs): expected_res_status=None, **kwargs):
defaults = {'name': 'sci1', 'description': 'test sci'} defaults = {'name': 'sci1', 'description': 'test sci'}
defaults.update(kwargs) defaults.update(kwargs)
data = {'servicechain_instance': { data = {'servicechain_instance':
'config_param_values': config_param_values, {'config_param_values': config_param_values,
'servicechain_spec': servicechain_spec, 'servicechain_spec': servicechain_spec,
'tenant_id': self._tenant_id, 'tenant_id': self._tenant_id,
'provider_epg': provider_epg, 'provider_ptg': provider_ptg,
'consumer_epg': consumer_epg, 'consumer_ptg': consumer_ptg,
'classifier': classifier}} 'classifier': classifier}}
data['servicechain_instance'].update(defaults) data['servicechain_instance'].update(defaults)
sci_req = self.new_create_request('servicechain_instances', sci_req = self.new_create_request('servicechain_instances',
@ -181,7 +181,7 @@ DB_GP_PLUGIN_KLASS = (ServiceChainDBTestPlugin.__module__ + '.' +
class ServiceChainDbTestCase(ServiceChainDBTestBase, class ServiceChainDbTestCase(ServiceChainDBTestBase,
test_db_plugin.NeutronDbPluginV2TestCase): test_db_plugin.NeutronDbPluginV2TestCase):
def setUp(self, core_plugin=None, sc_plugin=None, service_plugins=None, def setUp(self, core_plugin=None, sc_plugin=None, service_plugins=None,
ext_mgr=None): ext_mgr=None):
@ -216,10 +216,10 @@ class TestServiceChainResources(ServiceChainDbTestCase):
def test_create_and_show_servicechain_node(self): def test_create_and_show_servicechain_node(self):
attrs = self._get_test_servicechain_node_attrs( attrs = self._get_test_servicechain_node_attrs(
service_type=constants.LOADBALANCER, config="config1") service_type=constants.LOADBALANCER, config="config1")
scn = self.create_servicechain_node( scn = self.create_servicechain_node(
service_type=constants.LOADBALANCER, config="config1") service_type=constants.LOADBALANCER, config="config1")
for k, v in attrs.iteritems(): for k, v in attrs.iteritems():
self.assertEqual(scn['servicechain_node'][k], v) self.assertEqual(scn['servicechain_node'][k], v)
@ -230,8 +230,8 @@ class TestServiceChainResources(ServiceChainDbTestCase):
def test_list_servicechain_nodes(self): def test_list_servicechain_nodes(self):
scns = [self.create_servicechain_node(name='scn1', description='scn'), scns = [self.create_servicechain_node(name='scn1', description='scn'),
self.create_servicechain_node(name='scn2', description='scn'), self.create_servicechain_node(name='scn2', description='scn'),
self.create_servicechain_node(name='scn3', description='scn')] self.create_servicechain_node(name='scn3', description='scn')]
self._test_list_resources('servicechain_node', scns, self._test_list_resources('servicechain_node', scns,
query_params='description=scn') query_params='description=scn')
@ -327,22 +327,18 @@ class TestServiceChainResources(ServiceChainDbTestCase):
def test_create_and_show_servicechain_instance(self): def test_create_and_show_servicechain_instance(self):
scs_id = self.create_servicechain_spec()['servicechain_spec']['id'] scs_id = self.create_servicechain_spec()['servicechain_spec']['id']
endpoint_group_id = uuidutils.generate_uuid() policy_target_group_id = uuidutils.generate_uuid()
classifier_id = uuidutils.generate_uuid() classifier_id = uuidutils.generate_uuid()
config_param_values = "{}" config_param_values = "{}"
attrs = self._get_test_servicechain_instance_attrs( attrs = self._get_test_servicechain_instance_attrs(
servicechain_spec=scs_id, servicechain_spec=scs_id, provider_ptg=policy_target_group_id,
provider_epg=endpoint_group_id, consumer_ptg=policy_target_group_id, classifier=classifier_id,
consumer_epg=endpoint_group_id, config_param_values=config_param_values)
classifier=classifier_id,
config_param_values=config_param_values)
sci = self.create_servicechain_instance( sci = self.create_servicechain_instance(
servicechain_spec=scs_id, servicechain_spec=scs_id, provider_ptg=policy_target_group_id,
provider_epg=endpoint_group_id, consumer_ptg=policy_target_group_id, classifier=classifier_id,
consumer_epg=endpoint_group_id, config_param_values=config_param_values)
classifier=classifier_id,
config_param_values=config_param_values)
for k, v in attrs.iteritems(): for k, v in attrs.iteritems():
self.assertEqual(sci['servicechain_instance'][k], v) self.assertEqual(sci['servicechain_instance'][k], v)
@ -355,11 +351,9 @@ class TestServiceChainResources(ServiceChainDbTestCase):
def test_list_servicechain_instances(self): def test_list_servicechain_instances(self):
servicechain_instances = [self.create_servicechain_instance( servicechain_instances = [self.create_servicechain_instance(
name='sci1', description='sci'), name='sci1', description='sci'),
self.create_servicechain_instance(name='sci2', self.create_servicechain_instance(name='sci2', description='sci'),
description='sci'), self.create_servicechain_instance(name='sci3', description='sci')]
self.create_servicechain_instance(name='sci3',
description='sci')]
self._test_list_resources('servicechain_instance', self._test_list_resources('servicechain_instance',
servicechain_instances, servicechain_instances,
query_params='description=sci') query_params='description=sci')
@ -369,24 +363,18 @@ class TestServiceChainResources(ServiceChainDbTestCase):
description = 'new desc' description = 'new desc'
config_param_values = "{}" config_param_values = "{}"
scs_id = self.create_servicechain_spec()['servicechain_spec']['id'] scs_id = self.create_servicechain_spec()['servicechain_spec']['id']
provider_epg = uuidutils.generate_uuid() provider_ptg = uuidutils.generate_uuid()
consumer_epg = uuidutils.generate_uuid() consumer_ptg = uuidutils.generate_uuid()
classifier = uuidutils.generate_uuid() classifier = uuidutils.generate_uuid()
attrs = self._get_test_servicechain_instance_attrs( attrs = self._get_test_servicechain_instance_attrs(
name=name, name=name, description=description, servicechain_spec=scs_id,
description=description, provider_ptg=provider_ptg, consumer_ptg=consumer_ptg,
servicechain_spec=scs_id, classifier=classifier, config_param_values=config_param_values)
provider_epg=provider_epg,
consumer_epg=consumer_epg,
classifier=classifier,
config_param_values=config_param_values)
sci = self.create_servicechain_instance( sci = self.create_servicechain_instance(
servicechain_spec=scs_id, servicechain_spec=scs_id, provider_ptg=provider_ptg,
provider_epg=provider_epg, consumer_ptg=consumer_ptg, classifier=classifier,
consumer_epg=consumer_epg, config_param_values=config_param_values)
classifier=classifier,
config_param_values=config_param_values)
data = {'servicechain_instance': {'name': name, data = {'servicechain_instance': {'name': name,
'description': description, 'description': description,
'servicechain_spec': scs_id}} 'servicechain_spec': scs_id}}

View File

@ -29,7 +29,7 @@ from gbp.neutron.tests.unit.services.grouppolicy import test_grouppolicy_plugin
APIC_L2_POLICY = 'l2_policy' APIC_L2_POLICY = 'l2_policy'
APIC_L3_POLICY = 'l3_policy' APIC_L3_POLICY = 'l3_policy'
APIC_CONTRACT = 'contract' APIC_CONTRACT = 'contract'
APIC_ENDPOINT_GROUP = 'endpoint_group' APIC_ENDPOINT_GROUP = 'policy_target_group'
APIC_POLICY_RULE = 'policy_rule' APIC_POLICY_RULE = 'policy_rule'
CORE_PLUGIN = 'neutron.plugins.ml2.plugin.Ml2Plugin' CORE_PLUGIN = 'neutron.plugins.ml2.plugin.Ml2Plugin'
@ -68,10 +68,10 @@ class ApicMappingTestCase(
self.driver.name_mapper.tenant = echo self.driver.name_mapper.tenant = echo
self.driver.name_mapper.l2_policy = echo self.driver.name_mapper.l2_policy = echo
self.driver.name_mapper.l3_policy = echo self.driver.name_mapper.l3_policy = echo
self.driver.name_mapper.contract = echo self.driver.name_mapper.policy_rule_set = echo
self.driver.name_mapper.policy_rule = echo self.driver.name_mapper.policy_rule = echo
self.driver.name_mapper.app_profile.return_value = mocked.APIC_AP self.driver.name_mapper.app_profile.return_value = mocked.APIC_AP
self.driver.name_mapper.endpoint_group = echo self.driver.name_mapper.policy_target_group = echo
self.driver.apic_manager = mock.Mock(name_mapper=mock.Mock()) self.driver.apic_manager = mock.Mock(name_mapper=mock.Mock())
self.driver.apic_manager.apic.transaction = self.fake_transaction self.driver.apic_manager.apic.transaction = self.fake_transaction
@ -80,21 +80,23 @@ class ApicMappingTestCase(
return self.deserialize(self.fmt, req.get_response(api)) return self.deserialize(self.fmt, req.get_response(api))
class TestEndpoint(ApicMappingTestCase): class TestPolicyTarget(ApicMappingTestCase):
def test_endpoint_created_on_apic(self): def test_policy_target_created_on_apic(self):
epg = self.create_endpoint_group()['endpoint_group'] ptg = self.create_policy_target_group()['policy_target_group']
subnet = self._get_object('subnets', epg['subnets'][0], self.api) subnet = self._get_object('subnets', ptg['subnets'][0], self.api)
with self.port(subnet=subnet) as port: with self.port(subnet=subnet) as port:
self._bind_port_to_host(port['port']['id'], 'h1') self._bind_port_to_host(port['port']['id'], 'h1')
self.create_endpoint(epg['id'], port_id=port['port']['id']) self.create_policy_target(ptg['id'], port_id=port['port']['id'])
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
self.assertEqual(mgr.ensure_path_created_for_port.call_count, 1) self.assertEqual(mgr.ensure_path_created_for_port.call_count, 1)
def test_endpoint_port_update_on_apic_none_to_host(self): def test_policy_target_port_update_on_apic_none_to_host(self):
epg = self.create_endpoint_group(name="epg1")['endpoint_group'] ptg = self.create_policy_target_group(
ep = self.create_endpoint(endpoint_group_id=epg['id'])['endpoint'] name="ptg1")['policy_target_group']
port = self._get_object('ports', ep['port_id'], self.api) pt = self.create_policy_target(
policy_target_group_id=ptg['id'])['policy_target']
port = self._get_object('ports', pt['port_id'], self.api)
port_up = self._bind_port_to_host(port['port']['id'], 'h1') port_up = self._bind_port_to_host(port['port']['id'], 'h1')
self.driver.process_port_changed(context.get_admin_context(), self.driver.process_port_changed(context.get_admin_context(),
@ -102,24 +104,26 @@ class TestEndpoint(ApicMappingTestCase):
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
self.assertEqual(mgr.ensure_path_created_for_port.call_count, 1) self.assertEqual(mgr.ensure_path_created_for_port.call_count, 1)
def test_endpoint_port_deleted_on_apic(self): def test_policy_target_port_deleted_on_apic(self):
epg = self.create_endpoint_group()['endpoint_group'] ptg = self.create_policy_target_group()['policy_target_group']
subnet = self._get_object('subnets', epg['subnets'][0], self.api) subnet = self._get_object('subnets', ptg['subnets'][0], self.api)
with self.port(subnet=subnet) as port: with self.port(subnet=subnet) as port:
self._bind_port_to_host(port['port']['id'], 'h1') self._bind_port_to_host(port['port']['id'], 'h1')
ep = self.create_endpoint(epg['id'], port_id=port['port']['id']) pt = self.create_policy_target(
self.new_delete_request('endpoints', ep['endpoint']['id'], ptg['id'], port_id=port['port']['id'])
self.fmt).get_response(self.ext_api) self.new_delete_request(
'policy_targets', pt['policy_target']['id'],
self.fmt).get_response(self.ext_api)
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
self.assertEqual(mgr.ensure_path_deleted_for_port.call_count, 1) self.assertEqual(mgr.ensure_path_deleted_for_port.call_count, 1)
def test_endpoint_port_deleted_on_apic_host_to_host(self): def test_policy_target_port_deleted_on_apic_host_to_host(self):
epg = self.create_endpoint_group()['endpoint_group'] ptg = self.create_policy_target_group()['policy_target_group']
subnet = self._get_object('subnets', epg['subnets'][0], self.api) subnet = self._get_object('subnets', ptg['subnets'][0], self.api)
with self.port(subnet=subnet) as port: with self.port(subnet=subnet) as port:
# Create EP with bound port # Create EP with bound port
port = self._bind_port_to_host(port['port']['id'], 'h1') port = self._bind_port_to_host(port['port']['id'], 'h1')
self.create_endpoint(epg['id'], port_id=port['port']['id']) self.create_policy_target(ptg['id'], port_id=port['port']['id'])
# Change port binding and notify driver # Change port binding and notify driver
port_up = self._bind_port_to_host(port['port']['id'], 'h2') port_up = self._bind_port_to_host(port['port']['id'], 'h2')
@ -132,16 +136,19 @@ class TestEndpoint(ApicMappingTestCase):
# Path deleted 1 time # Path deleted 1 time
self.assertEqual(mgr.ensure_path_deleted_for_port.call_count, 1) self.assertEqual(mgr.ensure_path_deleted_for_port.call_count, 1)
def test_endpoint_port_not_deleted(self): def test_policy_target_port_not_deleted(self):
# Create 2 EP same EPG same host bound # Create 2 EP same EPG same host bound
epg = self.create_endpoint_group(name="epg1")['endpoint_group'] ptg = self.create_policy_target_group(
ep1 = self.create_endpoint(endpoint_group_id=epg['id'])['endpoint'] name="ptg1")['policy_target_group']
self._bind_port_to_host(ep1['port_id'], 'h1') pt1 = self.create_policy_target(
ep2 = self.create_endpoint(endpoint_group_id=epg['id'])['endpoint'] policy_target_group_id=ptg['id'])['policy_target']
self._bind_port_to_host(ep2['port_id'], 'h1') self._bind_port_to_host(pt1['port_id'], 'h1')
pt2 = self.create_policy_target(
policy_target_group_id=ptg['id'])['policy_target']
self._bind_port_to_host(pt2['port_id'], 'h1')
# Delete EP1 # Delete EP1
self.new_delete_request('endpoints', ep1['id'], self.new_delete_request('policy_targets', pt1['id'],
self.fmt).get_response(self.ext_api) self.fmt).get_response(self.ext_api)
# APIC path not deleted # APIC path not deleted
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
@ -155,106 +162,113 @@ class TestEndpoint(ApicMappingTestCase):
return self.deserialize(self.fmt, req.get_response(self.api)) return self.deserialize(self.fmt, req.get_response(self.api))
class TestEndpointGroup(ApicMappingTestCase): class TestPolicyTargetGroup(ApicMappingTestCase):
def test_endpoint_group_created_on_apic(self): def test_policy_target_group_created_on_apic(self):
epg = self.create_endpoint_group(name="epg1")['endpoint_group'] ptg = self.create_policy_target_group(
name="ptg1")['policy_target_group']
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
mgr.ensure_epg_created.assert_called_once_with( mgr.ensure_epg_created.assert_called_once_with(
epg['tenant_id'], epg['id'], bd_name=epg['l2_policy_id']) ptg['tenant_id'], ptg['id'], bd_name=ptg['l2_policy_id'])
def _test_epg_contract_created(self, provider=True): def _test_ptg_policy_rule_set_created(self, provider=True):
cntr = self.create_contract(name='c')['contract'] cntr = self.create_policy_rule_set(name='c')['policy_rule_set']
if provider: if provider:
epg = self.create_endpoint_group( ptg = self.create_policy_target_group(
provided_contracts={cntr['id']: 'scope'})['endpoint_group'] provided_policy_rule_sets={cntr['id']: 'scope'})[
'policy_target_group']
else: else:
epg = self.create_endpoint_group( ptg = self.create_policy_target_group(
consumed_contracts={cntr['id']: 'scope'})['endpoint_group'] consumed_policy_rule_sets={cntr['id']: 'scope'})[
'policy_target_group']
# Verify that the apic call is issued # Verify that the apic call is issued
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
mgr.set_contract_for_epg.assert_called_with( mgr.set_contract_for_epg.assert_called_with(
epg['tenant_id'], epg['id'], cntr['id'], transaction='transaction', ptg['tenant_id'], ptg['id'], cntr['id'], transaction='transaction',
provider=provider) provider=provider)
def _test_epg_contract_updated(self, provider=True): def _test_ptg_policy_rule_set_updated(self, provider=True):
p_or_c = {True: 'provided_contracts', False: 'consumed_contracts'} p_or_c = {True: 'provided_policy_rule_sets',
cntr = self.create_contract(name='c1')['contract'] False: 'consumed_policy_rule_sets'}
new_cntr = self.create_contract(name='c2')['contract'] cntr = self.create_policy_rule_set(name='c1')['policy_rule_set']
new_cntr = self.create_policy_rule_set(name='c2')['policy_rule_set']
if provider: if provider:
epg = self.create_endpoint_group( ptg = self.create_policy_target_group(
provided_contracts={cntr['id']: 'scope'}) provided_policy_rule_sets={cntr['id']: 'scope'})
else: else:
epg = self.create_endpoint_group( ptg = self.create_policy_target_group(
consumed_contracts={cntr['id']: 'scope'}) consumed_policy_rule_sets={cntr['id']: 'scope'})
data = {'endpoint_group': {p_or_c[provider]: data = {'policy_target_group': {p_or_c[provider]:
{new_cntr['id']: 'scope'}}} {new_cntr['id']: 'scope'}}}
req = self.new_update_request('endpoint_groups', data, req = self.new_update_request('policy_target_groups', data,
epg['endpoint_group']['id'], self.fmt) ptg['policy_target_group']['id'],
epg = self.deserialize(self.fmt, req.get_response(self.ext_api)) self.fmt)
epg = epg['endpoint_group'] ptg = self.deserialize(self.fmt, req.get_response(self.ext_api))
ptg = ptg['policy_target_group']
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
mgr.set_contract_for_epg.assert_called_with( mgr.set_contract_for_epg.assert_called_with(
epg['tenant_id'], epg['id'], new_cntr['id'], ptg['tenant_id'], ptg['id'], new_cntr['id'],
transaction='transaction', provider=provider) transaction='transaction', provider=provider)
mgr.unset_contract_for_epg.assert_called_with( mgr.unset_contract_for_epg.assert_called_with(
epg['tenant_id'], epg['id'], cntr['id'], ptg['tenant_id'], ptg['id'], cntr['id'],
transaction='transaction', provider=provider) transaction='transaction', provider=provider)
def test_epg_contract_provider_created(self): def test_ptg_policy_rule_set_provider_created(self):
self._test_epg_contract_created() self._test_ptg_policy_rule_set_created()
def test_epg_contract_provider_updated(self): def test_ptg_policy_rule_set_provider_updated(self):
self._test_epg_contract_updated() self._test_ptg_policy_rule_set_updated()
def test_epg_contract_consumer_created(self): def test_ptg_policy_rule_set_consumer_created(self):
self._test_epg_contract_created(False) self._test_ptg_policy_rule_set_created(False)
def test_epg_contract_consumer_updated(self): def test_ptg_policy_rule_set_consumer_updated(self):
self._test_epg_contract_updated(False) self._test_ptg_policy_rule_set_updated(False)
def test_endpoint_group_deleted_on_apic(self): def test_policy_target_group_deleted_on_apic(self):
epg = self.create_endpoint_group(name="epg1")['endpoint_group'] ptg = self.create_policy_target_group(
req = self.new_delete_request('endpoint_groups', epg['id'], self.fmt) name="ptg1")['policy_target_group']
req = self.new_delete_request(
'policy_target_groups', ptg['id'], self.fmt)
req.get_response(self.ext_api) req.get_response(self.ext_api)
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
mgr.delete_epg_for_network.assert_called_once_with( mgr.delete_epg_for_network.assert_called_once_with(
epg['tenant_id'], epg['id']) ptg['tenant_id'], ptg['id'])
def test_endpoint_group_subnet_created_on_apic(self): def test_policy_target_group_subnet_created_on_apic(self):
epg = self._create_explicit_subnet_epg('10.0.0.0/24') ptg = self._create_explicit_subnet_ptg('10.0.0.0/24')
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
mgr.ensure_subnet_created_on_apic.assert_called_once_with( mgr.ensure_subnet_created_on_apic.assert_called_once_with(
epg['tenant_id'], epg['l2_policy_id'], '10.0.0.1/24', ptg['tenant_id'], ptg['l2_policy_id'], '10.0.0.1/24',
transaction='transaction') transaction='transaction')
def test_endpoint_group_subnet_added(self): def test_policy_target_group_subnet_added(self):
epg = self._create_explicit_subnet_epg('10.0.0.0/24') ptg = self._create_explicit_subnet_ptg('10.0.0.0/24')
l2p = self._get_object('l2_policies', epg['l2_policy_id'], l2p = self._get_object('l2_policies', ptg['l2_policy_id'],
self.ext_api) self.ext_api)
network = self._get_object('networks', l2p['l2_policy']['network_id'], network = self._get_object('networks', l2p['l2_policy']['network_id'],
self.api) self.api)
with self.subnet(network=network, cidr='10.0.1.0/24') as subnet: with self.subnet(network=network, cidr='10.0.1.0/24') as subnet:
data = {'endpoint_group': data = {'policy_target_group':
{'subnets': epg['subnets'] + [subnet['subnet']['id']]}} {'subnets': ptg['subnets'] + [subnet['subnet']['id']]}}
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
self.new_update_request('endpoint_groups', data, epg['id'], self.new_update_request('policy_target_groups', data, ptg['id'],
self.fmt).get_response(self.ext_api) self.fmt).get_response(self.ext_api)
mgr.ensure_subnet_created_on_apic.assert_called_with( mgr.ensure_subnet_created_on_apic.assert_called_with(
epg['tenant_id'], epg['l2_policy_id'], '10.0.1.1/24', ptg['tenant_id'], ptg['l2_policy_id'], '10.0.1.1/24',
transaction='transaction') transaction='transaction')
def test_process_subnet_update(self): def test_process_subnet_update(self):
epg = self._create_explicit_subnet_epg('10.0.0.0/24') ptg = self._create_explicit_subnet_ptg('10.0.0.0/24')
subnet = self._get_object('subnets', epg['subnets'][0], self.api) subnet = self._get_object('subnets', ptg['subnets'][0], self.api)
subnet2 = copy.deepcopy(subnet) subnet2 = copy.deepcopy(subnet)
subnet2['subnet']['gateway_ip'] = '10.0.0.254' subnet2['subnet']['gateway_ip'] = '10.0.0.254'
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
@ -262,22 +276,22 @@ class TestEndpointGroup(ApicMappingTestCase):
self.driver.process_subnet_changed(context.get_admin_context(), self.driver.process_subnet_changed(context.get_admin_context(),
subnet['subnet'], subnet2['subnet']) subnet['subnet'], subnet2['subnet'])
mgr.ensure_subnet_created_on_apic.assert_called_once_with( mgr.ensure_subnet_created_on_apic.assert_called_once_with(
epg['tenant_id'], epg['l2_policy_id'], '10.0.0.254/24', ptg['tenant_id'], ptg['l2_policy_id'], '10.0.0.254/24',
transaction='transaction') transaction='transaction')
mgr.ensure_subnet_deleted_on_apic.assert_called_with( mgr.ensure_subnet_deleted_on_apic.assert_called_with(
epg['tenant_id'], epg['l2_policy_id'], '10.0.0.1/24', ptg['tenant_id'], ptg['l2_policy_id'], '10.0.0.1/24',
transaction='transaction') transaction='transaction')
def _create_explicit_subnet_epg(self, cidr): def _create_explicit_subnet_ptg(self, cidr):
l2p = self.create_l2_policy(name="l2p") l2p = self.create_l2_policy(name="l2p")
l2p_id = l2p['l2_policy']['id'] l2p_id = l2p['l2_policy']['id']
network_id = l2p['l2_policy']['network_id'] network_id = l2p['l2_policy']['network_id']
network = self._get_object('networks', network_id, self.api) network = self._get_object('networks', network_id, self.api)
with self.subnet(network=network, cidr=cidr) as subnet: with self.subnet(network=network, cidr=cidr) as subnet:
subnet_id = subnet['subnet']['id'] subnet_id = subnet['subnet']['id']
return self.create_endpoint_group( return self.create_policy_target_group(
name="epg1", l2_policy_id=l2p_id, name="ptg1", l2_policy_id=l2p_id,
subnets=[subnet_id])['endpoint_group'] subnets=[subnet_id])['policy_target_group']
class TestL2Policy(ApicMappingTestCase): class TestL2Policy(ApicMappingTestCase):
@ -317,22 +331,23 @@ class TestL3Policy(ApicMappingTestCase):
l3p['tenant_id'], l3p['id']) l3p['tenant_id'], l3p['id'])
class TestContract(ApicMappingTestCase): class TestPolicyRuleSet(ApicMappingTestCase):
# TODO(ivar): verify rule intersection with hierarchical contracts happens # TODO(ivar): verify rule intersection with hierarchical policy_rule_sets
# on APIC # happens on APIC
def test_contract_created_on_apic(self): def test_policy_rule_set_created_on_apic(self):
self.create_contract(name="ctr") self.create_policy_rule_set(name="ctr")
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
self.assertEqual(1, mgr.create_contract.call_count) self.assertEqual(1, mgr.create_contract.call_count)
def test_contract_created_with_rules(self): def test_policy_rule_set_created_with_rules(self):
bi, in_d, out = range(3) bi, in_d, out = range(3)
rules = self._create_3_direction_rules() rules = self._create_3_direction_rules()
# exclude BI rule for now # exclude BI rule for now
ctr = self.create_contract( ctr = self.create_policy_rule_set(
name="ctr", policy_rules=[x['id'] for x in rules[1:]])['contract'] name="ctr", policy_rules=[x['id'] for x in rules[1:]])[
'policy_rule_set']
# Verify that the in-out rules are correctly enforced on the APIC # Verify that the in-out rules are correctly enforced on the APIC
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
@ -343,9 +358,9 @@ class TestContract(ApicMappingTestCase):
ctr['id'], ctr['id'], rules[out]['id'], owner=ctr['tenant_id'], ctr['id'], ctr['id'], rules[out]['id'], owner=ctr['tenant_id'],
transaction='transaction', unset=False) transaction='transaction', unset=False)
# Create contract with BI rule # Create policy_rule_set with BI rule
ctr = self.create_contract( ctr = self.create_policy_rule_set(
name="ctr", policy_rules=[rules[bi]['id']])['contract'] name="ctr", policy_rules=[rules[bi]['id']])['policy_rule_set']
mgr.manage_contract_subject_in_filter.assert_called_with( mgr.manage_contract_subject_in_filter.assert_called_with(
ctr['id'], ctr['id'], rules[bi]['id'], owner=ctr['tenant_id'], ctr['id'], ctr['id'], rules[bi]['id'], owner=ctr['tenant_id'],
@ -354,20 +369,22 @@ class TestContract(ApicMappingTestCase):
ctr['id'], ctr['id'], rules[bi]['id'], owner=ctr['tenant_id'], ctr['id'], ctr['id'], rules[bi]['id'], owner=ctr['tenant_id'],
transaction='transaction', unset=False) transaction='transaction', unset=False)
def test_contract_updated_with_new_rules(self): def test_policy_rule_set_updated_with_new_rules(self):
bi, in_d, out = range(3) bi, in_d, out = range(3)
old_rules = self._create_3_direction_rules() old_rules = self._create_3_direction_rules()
new_rules = self._create_3_direction_rules() new_rules = self._create_3_direction_rules()
# exclude BI rule for now # exclude BI rule for now
ctr = self.create_contract( ctr = self.create_policy_rule_set(
name="ctr", name="ctr",
policy_rules=[x['id'] for x in old_rules[1:]])['contract'] policy_rules=[x['id'] for x in old_rules[1:]])['policy_rule_set']
data = {'contract': {'policy_rules': [x['id'] for x in new_rules[1:]]}} data = {'policy_rule_set':
{'policy_rules': [x['id'] for x in new_rules[1:]]}}
mgr = self.driver.apic_manager mgr = self.driver.apic_manager
mgr.manage_contract_subject_in_filter = MockCallRecorder() mgr.manage_contract_subject_in_filter = MockCallRecorder()
mgr.manage_contract_subject_out_filter = MockCallRecorder() mgr.manage_contract_subject_out_filter = MockCallRecorder()
self.new_update_request( self.new_update_request(
'contracts', data, ctr['id'], self.fmt).get_response(self.ext_api) 'policy_rule_sets', data, ctr['id'], self.fmt).get_response(
self.ext_api)
# Verify old IN rule unset and new IN rule set # Verify old IN rule unset and new IN rule set
self.assertTrue( self.assertTrue(
mgr.manage_contract_subject_in_filter.call_happened_with( mgr.manage_contract_subject_in_filter.call_happened_with(
@ -388,12 +405,13 @@ class TestContract(ApicMappingTestCase):
owner=ctr['tenant_id'], transaction='transaction', owner=ctr['tenant_id'], transaction='transaction',
unset=False)) unset=False))
ctr = self.create_contract( ctr = self.create_policy_rule_set(
name="ctr", name="ctr",
policy_rules=[old_rules[0]['id']])['contract'] policy_rules=[old_rules[0]['id']])['policy_rule_set']
data = {'contract': {'policy_rules': [new_rules[0]['id']]}} data = {'policy_rule_set': {'policy_rules': [new_rules[0]['id']]}}
self.new_update_request( self.new_update_request(
'contracts', data, ctr['id'], self.fmt).get_response(self.ext_api) 'policy_rule_sets', data, ctr['id'], self.fmt).get_response(
self.ext_api)
# Verify old BI rule unset and new Bu rule set # Verify old BI rule unset and new Bu rule set
self.assertTrue( self.assertTrue(
mgr.manage_contract_subject_in_filter.call_happened_with( mgr.manage_contract_subject_in_filter.call_happened_with(
@ -465,4 +483,4 @@ class TestPolicyRule(ApicMappingTestCase):
action = self.create_policy_action( action = self.create_policy_action(
action_type='allow')['policy_action'] action_type='allow')['policy_action']
return self.create_policy_rule( return self.create_policy_rule(
cls['id'], policy_actions=[action['id']])['policy_rule'] cls['id'], policy_actions=[action['id']])['policy_rule']

View File

@ -64,10 +64,11 @@ class GroupPolicyPluginTestCase(tgpmdb.GroupPolicyMappingDbTestCase):
finally: finally:
manager.ordered_policy_drivers = drivers manager.ordered_policy_drivers = drivers
def test_delete_fails_on_used_epg(self): def test_delete_fails_on_used_ptg(self):
epg = self.create_endpoint_group()['endpoint_group'] ptg = self.create_policy_target_group()['policy_target_group']
self.create_endpoint(endpoint_group_id=epg['id']) self.create_policy_target(policy_target_group_id=ptg['id'])
req = self.new_delete_request('endpoint_groups', epg['id'], self.fmt) req = self.new_delete_request('policy_target_groups', ptg['id'],
self.fmt)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, 400) self.assertEqual(res.status_int, 400)

View File

@ -30,38 +30,39 @@ class ImplicitPolicyTestCase(
class TestImplicitL2Policy(ImplicitPolicyTestCase): class TestImplicitL2Policy(ImplicitPolicyTestCase):
def test_impicit_lifecycle(self): def test_impicit_lifecycle(self):
# Create endpoint group with implicit L2 policy. # Create policy_target group with implicit L2 policy.
epg1 = self.create_endpoint_group() ptg1 = self.create_policy_target_group()
epg1_id = epg1['endpoint_group']['id'] ptg1_id = ptg1['policy_target_group']['id']
l2p1_id = epg1['endpoint_group']['l2_policy_id'] l2p1_id = ptg1['policy_target_group']['l2_policy_id']
self.assertIsNotNone(l2p1_id) self.assertIsNotNone(l2p1_id)
req = self.new_show_request('endpoint_groups', epg1_id, fmt=self.fmt) req = self.new_show_request('policy_target_groups', ptg1_id,
fmt=self.fmt)
res = self.deserialize(self.fmt, req.get_response(self.ext_api)) res = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(l2p1_id, res['endpoint_group']['l2_policy_id']) self.assertEqual(l2p1_id, res['policy_target_group']['l2_policy_id'])
req = self.new_show_request('l2_policies', l2p1_id, fmt=self.fmt) req = self.new_show_request('l2_policies', l2p1_id, fmt=self.fmt)
l2p1 = self.deserialize(self.fmt, req.get_response(self.ext_api)) l2p1 = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(epg1['endpoint_group']['name'], self.assertEqual(ptg1['policy_target_group']['name'],
l2p1['l2_policy']['name']) l2p1['l2_policy']['name'])
# Create 2nd endpoint group with different implicit L2 policy. # Create 2nd policy_target group with different implicit L2 policy.
epg2 = self.create_endpoint_group() ptg2 = self.create_policy_target_group()
epg2_id = epg2['endpoint_group']['id'] ptg2_id = ptg2['policy_target_group']['id']
l2p2_id = epg2['endpoint_group']['l2_policy_id'] l2p2_id = ptg2['policy_target_group']['l2_policy_id']
self.assertIsNotNone(l2p2_id) self.assertIsNotNone(l2p2_id)
self.assertNotEqual(l2p1_id, l2p2_id) self.assertNotEqual(l2p1_id, l2p2_id)
# Verify deleting 1st endpoint group does cleanup its L2 # Verify deleting 1st policy_target group does cleanup its L2
# policy. # policy.
req = self.new_delete_request('endpoint_groups', epg1_id) req = self.new_delete_request('policy_target_groups', ptg1_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
req = self.new_show_request('l2_policies', l2p1_id, fmt=self.fmt) req = self.new_show_request('l2_policies', l2p1_id, fmt=self.fmt)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNotFound.code) self.assertEqual(res.status_int, webob.exc.HTTPNotFound.code)
# Verify deleting 2nd endpoint group does cleanup its L2 # Verify deleting 2nd policy_target group does cleanup its L2
# policy. # policy.
req = self.new_delete_request('endpoint_groups', epg2_id) req = self.new_delete_request('policy_target_groups', ptg2_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
req = self.new_show_request('l2_policies', l2p2_id, fmt=self.fmt) req = self.new_show_request('l2_policies', l2p2_id, fmt=self.fmt)
@ -69,15 +70,15 @@ class TestImplicitL2Policy(ImplicitPolicyTestCase):
self.assertEqual(res.status_int, webob.exc.HTTPNotFound.code) self.assertEqual(res.status_int, webob.exc.HTTPNotFound.code)
def test_explicit_lifecycle(self): def test_explicit_lifecycle(self):
# Create endpoint group with explicit L2 policy. # Create policy_target group with explicit L2 policy.
l2p = self.create_l2_policy() l2p = self.create_l2_policy()
l2p_id = l2p['l2_policy']['id'] l2p_id = l2p['l2_policy']['id']
epg = self.create_endpoint_group(l2_policy_id=l2p_id) ptg = self.create_policy_target_group(l2_policy_id=l2p_id)
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
self.assertEqual(l2p_id, epg['endpoint_group']['l2_policy_id']) self.assertEqual(l2p_id, ptg['policy_target_group']['l2_policy_id'])
# Verify deleting endpoint group does not cleanup L2 policy. # Verify deleting policy_target group does not cleanup L2 policy.
req = self.new_delete_request('endpoint_groups', epg_id) req = self.new_delete_request('policy_target_groups', ptg_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
req = self.new_show_request('l2_policies', l2p_id, fmt=self.fmt) req = self.new_show_request('l2_policies', l2p_id, fmt=self.fmt)
@ -85,31 +86,31 @@ class TestImplicitL2Policy(ImplicitPolicyTestCase):
self.assertEqual(res.status_int, webob.exc.HTTPOk.code) self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
def test_update_from_implicit(self): def test_update_from_implicit(self):
# Create endpoint group with implicit L2 policy. # Create policy_target group with implicit L2 policy.
epg = self.create_endpoint_group() ptg = self.create_policy_target_group()
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
l2p1_id = epg['endpoint_group']['l2_policy_id'] l2p1_id = ptg['policy_target_group']['l2_policy_id']
req = self.new_show_request('l2_policies', l2p1_id, fmt=self.fmt) req = self.new_show_request('l2_policies', l2p1_id, fmt=self.fmt)
l2p1 = self.deserialize(self.fmt, req.get_response(self.ext_api)) l2p1 = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(epg['endpoint_group']['name'], self.assertEqual(ptg['policy_target_group']['name'],
l2p1['l2_policy']['name']) l2p1['l2_policy']['name'])
# Update endpoint group to explicit L2 policy. # Update policy_target group to explicit L2 policy.
l2p2 = self.create_l2_policy() l2p2 = self.create_l2_policy()
l2p2_id = l2p2['l2_policy']['id'] l2p2_id = l2p2['l2_policy']['id']
data = {'endpoint_group': {'l2_policy_id': l2p2_id}} data = {'policy_target_group': {'l2_policy_id': l2p2_id}}
req = self.new_update_request('endpoint_groups', data, epg_id) req = self.new_update_request('policy_target_groups', data, ptg_id)
epg = self.deserialize(self.fmt, req.get_response(self.ext_api)) ptg = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(l2p2_id, epg['endpoint_group']['l2_policy_id']) self.assertEqual(l2p2_id, ptg['policy_target_group']['l2_policy_id'])
# Verify old L2 policy was cleaned up. # Verify old L2 policy was cleaned up.
req = self.new_show_request('l2_policies', l2p1_id, fmt=self.fmt) req = self.new_show_request('l2_policies', l2p1_id, fmt=self.fmt)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNotFound.code) self.assertEqual(res.status_int, webob.exc.HTTPNotFound.code)
# Verify deleting endpoint group does not cleanup new L2 # Verify deleting policy_target group does not cleanup new L2
# policy. # policy.
req = self.new_delete_request('endpoint_groups', epg_id) req = self.new_delete_request('policy_target_groups', ptg_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
req = self.new_show_request('l2_policies', l2p2_id, fmt=self.fmt) req = self.new_show_request('l2_policies', l2p2_id, fmt=self.fmt)
@ -117,23 +118,23 @@ class TestImplicitL2Policy(ImplicitPolicyTestCase):
self.assertEqual(res.status_int, webob.exc.HTTPOk.code) self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
def test_update_to_implicit(self): def test_update_to_implicit(self):
# Create endpoint group with explicit L2 policy. # Create policy_target group with explicit L2 policy.
l2p1 = self.create_l2_policy() l2p1 = self.create_l2_policy()
l2p1_id = l2p1['l2_policy']['id'] l2p1_id = l2p1['l2_policy']['id']
epg = self.create_endpoint_group(l2_policy_id=l2p1_id) ptg = self.create_policy_target_group(l2_policy_id=l2p1_id)
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
self.assertEqual(l2p1_id, epg['endpoint_group']['l2_policy_id']) self.assertEqual(l2p1_id, ptg['policy_target_group']['l2_policy_id'])
# Update endpoint group to implicit L2 policy. # Update policy_target group to implicit L2 policy.
data = {'endpoint_group': {'l2_policy_id': None}} data = {'policy_target_group': {'l2_policy_id': None}}
req = self.new_update_request('endpoint_groups', data, epg_id) req = self.new_update_request('policy_target_groups', data, ptg_id)
epg = self.deserialize(self.fmt, req.get_response(self.ext_api)) ptg = self.deserialize(self.fmt, req.get_response(self.ext_api))
l2p2_id = epg['endpoint_group']['l2_policy_id'] l2p2_id = ptg['policy_target_group']['l2_policy_id']
self.assertNotEqual(l2p1_id, l2p2_id) self.assertNotEqual(l2p1_id, l2p2_id)
self.assertIsNotNone(l2p2_id) self.assertIsNotNone(l2p2_id)
req = self.new_show_request('l2_policies', l2p2_id, fmt=self.fmt) req = self.new_show_request('l2_policies', l2p2_id, fmt=self.fmt)
l2p2 = self.deserialize(self.fmt, req.get_response(self.ext_api)) l2p2 = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual(epg['endpoint_group']['name'], self.assertEqual(ptg['policy_target_group']['name'],
l2p2['l2_policy']['name']) l2p2['l2_policy']['name'])
# Verify old L2 policy was not cleaned up. # Verify old L2 policy was not cleaned up.
@ -141,8 +142,8 @@ class TestImplicitL2Policy(ImplicitPolicyTestCase):
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPOk.code) self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
# Verify deleting endpoint group does cleanup new L2 policy. # Verify deleting policy_target group does cleanup new L2 policy.
req = self.new_delete_request('endpoint_groups', epg_id) req = self.new_delete_request('policy_target_groups', ptg_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
req = self.new_show_request('l2_policies', l2p2_id, fmt=self.fmt) req = self.new_show_request('l2_policies', l2p2_id, fmt=self.fmt)

View File

@ -29,8 +29,9 @@ from gbp.neutron.services.servicechain import servicechain_plugin
from gbp.neutron.tests.unit.services.grouppolicy import test_grouppolicy_plugin from gbp.neutron.tests.unit.services.grouppolicy import test_grouppolicy_plugin
class NoL3NatSGTestPlugin(test_l3_plugin.TestNoL3NatPlugin, class NoL3NatSGTestPlugin(
test_extension_security_group.SecurityGroupTestPlugin): test_l3_plugin.TestNoL3NatPlugin,
test_extension_security_group.SecurityGroupTestPlugin):
supported_extension_aliases = ["external-net", "security-group"] supported_extension_aliases = ["external-net", "security-group"]
@ -49,24 +50,25 @@ class ResourceMappingTestCase(
super(ResourceMappingTestCase, self).setUp(core_plugin=CORE_PLUGIN) super(ResourceMappingTestCase, self).setUp(core_plugin=CORE_PLUGIN)
class TestEndpoint(ResourceMappingTestCase): class TestPolicyTarget(ResourceMappingTestCase):
def test_implicit_port_lifecycle(self): def test_implicit_port_lifecycle(self):
# Create endpoint group. # Create policy_target group.
epg = self.create_endpoint_group(name="epg1") ptg = self.create_policy_target_group(name="ptg1")
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
# Create endpoint with implicit port. # Create policy_target with implicit port.
ep = self.create_endpoint(name="ep1", endpoint_group_id=epg_id) pt = self.create_policy_target(name="pt1",
ep_id = ep['endpoint']['id'] policy_target_group_id=ptg_id)
port_id = ep['endpoint']['port_id'] pt_id = pt['policy_target']['id']
port_id = pt['policy_target']['port_id']
self.assertIsNotNone(port_id) self.assertIsNotNone(port_id)
# TODO(rkukura): Verify implicit port belongs to endpoint # TODO(rkukura): Verify implicit port belongs to policy_target
# group's subnet. # group's subnet.
# Verify deleting endpoint cleans up port. # Verify deleting policy_target cleans up port.
req = self.new_delete_request('endpoints', ep_id) req = self.new_delete_request('policy_targets', pt_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
req = self.new_show_request('ports', port_id, fmt=self.fmt) req = self.new_show_request('ports', port_id, fmt=self.fmt)
@ -74,67 +76,67 @@ class TestEndpoint(ResourceMappingTestCase):
self.assertEqual(res.status_int, webob.exc.HTTPNotFound.code) self.assertEqual(res.status_int, webob.exc.HTTPNotFound.code)
def test_explicit_port_lifecycle(self): def test_explicit_port_lifecycle(self):
# Create endpoint group. # Create policy_target group.
epg = self.create_endpoint_group(name="epg1") ptg = self.create_policy_target_group(name="ptg1")
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
subnet_id = epg['endpoint_group']['subnets'][0] subnet_id = ptg['policy_target_group']['subnets'][0]
req = self.new_show_request('subnets', subnet_id) req = self.new_show_request('subnets', subnet_id)
subnet = self.deserialize(self.fmt, req.get_response(self.api)) subnet = self.deserialize(self.fmt, req.get_response(self.api))
# Create endpoint with explicit port. # Create policy_target with explicit port.
with self.port(subnet=subnet) as port: with self.port(subnet=subnet) as port:
port_id = port['port']['id'] port_id = port['port']['id']
ep = self.create_endpoint(name="ep1", endpoint_group_id=epg_id, pt = self.create_policy_target(
port_id=port_id) name="pt1", policy_target_group_id=ptg_id, port_id=port_id)
ep_id = ep['endpoint']['id'] pt_id = pt['policy_target']['id']
self.assertEqual(port_id, ep['endpoint']['port_id']) self.assertEqual(port_id, pt['policy_target']['port_id'])
# Verify deleting endpoint does not cleanup port. # Verify deleting policy_target does not cleanup port.
req = self.new_delete_request('endpoints', ep_id) req = self.new_delete_request('policy_targets', pt_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
req = self.new_show_request('ports', port_id, fmt=self.fmt) req = self.new_show_request('ports', port_id, fmt=self.fmt)
res = req.get_response(self.api) res = req.get_response(self.api)
self.assertEqual(res.status_int, webob.exc.HTTPOk.code) self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
def test_missing_epg_rejected(self): def test_missing_ptg_rejected(self):
data = self.create_endpoint(name="ep1", data = self.create_policy_target(
expected_res_status= name="pt1", expected_res_status=webob.exc.HTTPBadRequest.code)
webob.exc.HTTPBadRequest.code) self.assertEqual('PolicyTargetRequiresPolicyTargetGroup',
self.assertEqual('EndpointRequiresEndpointGroup',
data['NeutronError']['type']) data['NeutronError']['type'])
def test_epg_update_rejected(self): def test_ptg_update_rejected(self):
# Create two endpoint groups. # Create two policy_target groups.
epg1 = self.create_endpoint_group(name="epg1") ptg1 = self.create_policy_target_group(name="ptg1")
epg1_id = epg1['endpoint_group']['id'] ptg1_id = ptg1['policy_target_group']['id']
epg2 = self.create_endpoint_group(name="epg2") ptg2 = self.create_policy_target_group(name="ptg2")
epg2_id = epg2['endpoint_group']['id'] ptg2_id = ptg2['policy_target_group']['id']
# Create endpoint. # Create policy_target.
ep = self.create_endpoint(name="ep1", endpoint_group_id=epg1_id) pt = self.create_policy_target(name="pt1",
ep_id = ep['endpoint']['id'] policy_target_group_id=ptg1_id)
pt_id = pt['policy_target']['id']
# Verify updating endpoint group rejected. # Verify updating policy_target group rejected.
data = {'endpoint': {'endpoint_group_id': epg2_id}} data = {'policy_target': {'policy_target_group_id': ptg2_id}}
req = self.new_update_request('endpoints', data, ep_id) req = self.new_update_request('policy_targets', data, pt_id)
data = self.deserialize(self.fmt, req.get_response(self.ext_api)) data = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual('EndpointEndpointGroupUpdateNotSupported', self.assertEqual('PolicyTargetGroupUpdateOfPolicyTargetNotSupported',
data['NeutronError']['type']) data['NeutronError']['type'])
class TestEndpointGroup(ResourceMappingTestCase): class TestPolicyTargetGroup(ResourceMappingTestCase):
def test_implicit_subnet_lifecycle(self): def test_implicit_subnet_lifecycle(self):
# Use explicit L2 policy so network and subnet not deleted # Use explicit L2 policy so network and subnet not deleted
# with endpoint group. # with policy_target group.
l2p = self.create_l2_policy() l2p = self.create_l2_policy()
l2p_id = l2p['l2_policy']['id'] l2p_id = l2p['l2_policy']['id']
# Create endpoint group with implicit subnet. # Create policy_target group with implicit subnet.
epg = self.create_endpoint_group(name="epg1", l2_policy_id=l2p_id) ptg = self.create_policy_target_group(name="ptg1", l2_policy_id=l2p_id)
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
subnets = epg['endpoint_group']['subnets'] subnets = ptg['policy_target_group']['subnets']
self.assertIsNotNone(subnets) self.assertIsNotNone(subnets)
self.assertEqual(len(subnets), 1) self.assertEqual(len(subnets), 1)
subnet_id = subnets[0] subnet_id = subnets[0]
@ -143,8 +145,8 @@ class TestEndpointGroup(ResourceMappingTestCase):
# network, is within L3 policy's ip_pool, and was added as # network, is within L3 policy's ip_pool, and was added as
# router interface. # router interface.
# Verify deleting endpoint group cleans up subnet. # Verify deleting policy_target group cleans up subnet.
req = self.new_delete_request('endpoint_groups', epg_id) req = self.new_delete_request('policy_target_groups', ptg_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
req = self.new_show_request('subnets', subnet_id, fmt=self.fmt) req = self.new_show_request('subnets', subnet_id, fmt=self.fmt)
@ -166,13 +168,13 @@ class TestEndpointGroup(ResourceMappingTestCase):
req = self.new_show_request('networks', network_id) req = self.new_show_request('networks', network_id)
network = self.deserialize(self.fmt, req.get_response(self.api)) network = self.deserialize(self.fmt, req.get_response(self.api))
# Create endpoint group with explicit subnet. # Create policy_target group with explicit subnet.
with self.subnet(network=network, cidr='10.10.1.0/24') as subnet: with self.subnet(network=network, cidr='10.10.1.0/24') as subnet:
subnet_id = subnet['subnet']['id'] subnet_id = subnet['subnet']['id']
epg = self.create_endpoint_group(name="epg1", l2_policy_id=l2p_id, ptg = self.create_policy_target_group(
subnets=[subnet_id]) name="ptg1", l2_policy_id=l2p_id, subnets=[subnet_id])
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
subnets = epg['endpoint_group']['subnets'] subnets = ptg['policy_target_group']['subnets']
self.assertIsNotNone(subnets) self.assertIsNotNone(subnets)
self.assertEqual(len(subnets), 1) self.assertEqual(len(subnets), 1)
self.assertEqual(subnet_id, subnets[0]) self.assertEqual(subnet_id, subnets[0])
@ -180,8 +182,8 @@ class TestEndpointGroup(ResourceMappingTestCase):
# TODO(rkukura): Verify explicit subnet was added as # TODO(rkukura): Verify explicit subnet was added as
# router interface. # router interface.
# Verify deleting endpoint group does not cleanup subnet. # Verify deleting policy_target group does not cleanup subnet.
req = self.new_delete_request('endpoint_groups', epg_id) req = self.new_delete_request('policy_target_groups', ptg_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)
req = self.new_show_request('subnets', subnet_id, fmt=self.fmt) req = self.new_show_request('subnets', subnet_id, fmt=self.fmt)
@ -203,7 +205,7 @@ class TestEndpointGroup(ResourceMappingTestCase):
req = self.new_show_request('networks', network_id) req = self.new_show_request('networks', network_id)
network = self.deserialize(self.fmt, req.get_response(self.api)) network = self.deserialize(self.fmt, req.get_response(self.api))
# Create endpoint group with explicit subnet. # Create policy_target group with explicit subnet.
with contextlib.nested( with contextlib.nested(
self.subnet(network=network, cidr='10.10.1.0/24'), self.subnet(network=network, cidr='10.10.1.0/24'),
self.subnet(network=network, cidr='10.10.2.0/24') self.subnet(network=network, cidr='10.10.2.0/24')
@ -211,14 +213,14 @@ class TestEndpointGroup(ResourceMappingTestCase):
subnet1_id = subnet1['subnet']['id'] subnet1_id = subnet1['subnet']['id']
subnet2_id = subnet2['subnet']['id'] subnet2_id = subnet2['subnet']['id']
subnets = [subnet1_id] subnets = [subnet1_id]
epg = self.create_endpoint_group(l2_policy_id=l2p_id, ptg = self.create_policy_target_group(
subnets=subnets) l2_policy_id=l2p_id, subnets=subnets)
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
# Add subnet. # Add subnet.
subnets = [subnet1_id, subnet2_id] subnets = [subnet1_id, subnet2_id]
data = {'endpoint_group': {'subnets': subnets}} data = {'policy_target_group': {'subnets': subnets}}
req = self.new_update_request('endpoint_groups', data, epg_id) req = self.new_update_request('policy_target_groups', data, ptg_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPOk.code) self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
@ -234,7 +236,7 @@ class TestEndpointGroup(ResourceMappingTestCase):
req = self.new_show_request('networks', network_id) req = self.new_show_request('networks', network_id)
network = self.deserialize(self.fmt, req.get_response(self.api)) network = self.deserialize(self.fmt, req.get_response(self.api))
# Create endpoint group with explicit subnets. # Create policy_target group with explicit subnets.
with contextlib.nested( with contextlib.nested(
self.subnet(network=network, cidr='10.10.1.0/24'), self.subnet(network=network, cidr='10.10.1.0/24'),
self.subnet(network=network, cidr='10.10.2.0/24') self.subnet(network=network, cidr='10.10.2.0/24')
@ -242,25 +244,25 @@ class TestEndpointGroup(ResourceMappingTestCase):
subnet1_id = subnet1['subnet']['id'] subnet1_id = subnet1['subnet']['id']
subnet2_id = subnet2['subnet']['id'] subnet2_id = subnet2['subnet']['id']
subnets = [subnet1_id, subnet2_id] subnets = [subnet1_id, subnet2_id]
epg = self.create_endpoint_group(l2_policy_id=l2p_id, ptg = self.create_policy_target_group(
subnets=subnets) l2_policy_id=l2p_id, subnets=subnets)
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
# Verify removing subnet rejected. # Verify removing subnet rejected.
data = {'endpoint_group': {'subnets': [subnet2_id]}} data = {'policy_target_group': {'subnets': [subnet2_id]}}
req = self.new_update_request('endpoint_groups', data, epg_id) req = self.new_update_request('policy_target_groups', data, ptg_id)
data = self.deserialize(self.fmt, req.get_response(self.ext_api)) data = self.deserialize(self.fmt, req.get_response(self.ext_api))
self.assertEqual('EndpointGroupSubnetRemovalNotSupported', self.assertEqual('PolicyTargetGroupSubnetRemovalNotSupported',
data['NeutronError']['type']) data['NeutronError']['type'])
def test_subnet_allocation(self): def test_subnet_allocation(self):
epg1 = self.create_endpoint_group(name="epg1") ptg1 = self.create_policy_target_group(name="ptg1")
subnets = epg1['endpoint_group']['subnets'] subnets = ptg1['policy_target_group']['subnets']
req = self.new_show_request('subnets', subnets[0], fmt=self.fmt) req = self.new_show_request('subnets', subnets[0], fmt=self.fmt)
subnet1 = self.deserialize(self.fmt, req.get_response(self.api)) subnet1 = self.deserialize(self.fmt, req.get_response(self.api))
epg2 = self.create_endpoint_group(name="epg2") ptg2 = self.create_policy_target_group(name="ptg2")
subnets = epg2['endpoint_group']['subnets'] subnets = ptg2['policy_target_group']['subnets']
req = self.new_show_request('subnets', subnets[0], fmt=self.fmt) req = self.new_show_request('subnets', subnets[0], fmt=self.fmt)
subnet2 = self.deserialize(self.fmt, req.get_response(self.api)) subnet2 = self.deserialize(self.fmt, req.get_response(self.api))
@ -375,10 +377,12 @@ class NotificationTest(ResourceMappingTestCase):
def test_dhcp_notifier(self): def test_dhcp_notifier(self):
with mock.patch.object(dhcp_rpc_agent_api.DhcpAgentNotifyAPI, with mock.patch.object(dhcp_rpc_agent_api.DhcpAgentNotifyAPI,
'notify') as dhcp_notifier: 'notify') as dhcp_notifier:
epg = self.create_endpoint_group(name="epg1") ptg = self.create_policy_target_group(name="ptg1")
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
ep = self.create_endpoint(name="ep1", endpoint_group_id=epg_id) pt = self.create_policy_target(
self.assertEqual(ep['endpoint']['endpoint_group_id'], epg_id) name="pt1", policy_target_group_id=ptg_id)
self.assertEqual(
pt['policy_target']['policy_target_group_id'], ptg_id)
# REVISIT(rkukura): Check dictionaries for correct id, etc.. # REVISIT(rkukura): Check dictionaries for correct id, etc..
dhcp_notifier.assert_any_call(mock.ANY, mock.ANY, dhcp_notifier.assert_any_call(mock.ANY, mock.ANY,
"router.create.end") "router.create.end")
@ -392,10 +396,12 @@ class NotificationTest(ResourceMappingTestCase):
def test_nova_notifier(self): def test_nova_notifier(self):
with mock.patch.object(nova.Notifier, with mock.patch.object(nova.Notifier,
'send_network_change') as nova_notifier: 'send_network_change') as nova_notifier:
epg = self.create_endpoint_group(name="epg1") ptg = self.create_policy_target_group(name="ptg1")
epg_id = epg['endpoint_group']['id'] ptg_id = ptg['policy_target_group']['id']
ep = self.create_endpoint(name="ep1", endpoint_group_id=epg_id) pt = self.create_policy_target(
self.assertEqual(ep['endpoint']['endpoint_group_id'], epg_id) name="pt1", policy_target_group_id=ptg_id)
self.assertEqual(
pt['policy_target']['policy_target_group_id'], ptg_id)
# REVISIT(rkukura): Check dictionaries for correct id, etc.. # REVISIT(rkukura): Check dictionaries for correct id, etc..
nova_notifier.assert_any_call("create_router", {}, mock.ANY) nova_notifier.assert_any_call("create_router", {}, mock.ANY)
nova_notifier.assert_any_call("create_network", {}, mock.ANY) nova_notifier.assert_any_call("create_network", {}, mock.ANY)
@ -403,34 +409,37 @@ class NotificationTest(ResourceMappingTestCase):
nova_notifier.assert_any_call("create_port", {}, mock.ANY) nova_notifier.assert_any_call("create_port", {}, mock.ANY)
# TODO(ivar): We need a UT that verifies that the EP's ports have the default # TODO(ivar): We need a UT that verifies that the PT's ports have the default
# SG when there are no contracts involved, that the default SG is properly # SG when there are no policy_rule_sets involved, that the default SG is
# created and shared, and that it has the right content. # properly # created and shared, and that it has the right content.
class TestContract(ResourceMappingTestCase): class TestPolicyRuleSet(ResourceMappingTestCase):
def test_contract_creation(self): def test_policy_rule_set_creation(self):
# Create contracts # Create policy_rule_sets
classifier = self.create_policy_classifier(name="class1", classifier = self.create_policy_classifier(
protocol="tcp", direction="out", port_range="50:100") name="class1", protocol="tcp", direction="out",
port_range="50:100")
classifier_id = classifier['policy_classifier']['id'] classifier_id = classifier['policy_classifier']['id']
action = self.create_policy_action(name="action1") action = self.create_policy_action(name="action1")
action_id = action['policy_action']['id'] action_id = action['policy_action']['id']
action_id_list = [action_id] action_id_list = [action_id]
policy_rule = self.create_policy_rule(name='pr1', policy_rule = self.create_policy_rule(
policy_classifier_id=classifier_id, name='pr1', policy_classifier_id=classifier_id,
policy_actions=action_id_list) policy_actions=action_id_list)
policy_rule_id = policy_rule['policy_rule']['id'] policy_rule_id = policy_rule['policy_rule']['id']
policy_rule_list = [policy_rule_id] policy_rule_list = [policy_rule_id]
contract = self.create_contract(name="c1", policy_rule_set = self.create_policy_rule_set(
policy_rules=policy_rule_list) name="c1", policy_rules=policy_rule_list)
contract_id = contract['contract']['id'] policy_rule_set_id = policy_rule_set['policy_rule_set']['id']
epg = self.create_endpoint_group(name="epg1", ptg = self.create_policy_target_group(
provided_contracts={contract_id: None}) name="ptg1", provided_policy_rule_sets={
epg_id = epg['endpoint_group']['id'] policy_rule_set_id: None})
ep = self.create_endpoint(name="ep1", endpoint_group_id=epg_id) ptg_id = ptg['policy_target_group']['id']
pt = self.create_policy_target(
name="pt1", policy_target_group_id=ptg_id)
# verify SG bind to port # verify SG bind to port
port_id = ep['endpoint']['port_id'] port_id = pt['policy_target']['port_id']
res = self.new_show_request('ports', port_id) res = self.new_show_request('ports', port_id)
port = self.deserialize(self.fmt, res.get_response(self.api)) port = self.deserialize(self.fmt, res.get_response(self.api))
security_groups = port['port'][ext_sg.SECURITYGROUPS] security_groups = port['port'][ext_sg.SECURITYGROUPS]
@ -438,169 +447,170 @@ class TestContract(ResourceMappingTestCase):
# TODO(ivar): we also need to verify that those security groups have the # TODO(ivar): we also need to verify that those security groups have the
# right rules # right rules
def test_consumed_contract(self): def test_consumed_policy_rule_set(self):
classifier = self.create_policy_classifier(name="class1", classifier = self.create_policy_classifier(
protocol="tcp", direction="in", port_range="20:90") name="class1", protocol="tcp", direction="in", port_range="20:90")
classifier_id = classifier['policy_classifier']['id'] classifier_id = classifier['policy_classifier']['id']
action = self.create_policy_action(name="action1", action = self.create_policy_action(name="action1",
action_type=gconst.GP_ACTION_ALLOW) action_type=gconst.GP_ACTION_ALLOW)
action_id = action['policy_action']['id'] action_id = action['policy_action']['id']
action_id_list = [action_id] action_id_list = [action_id]
policy_rule = self.create_policy_rule(name='pr1', policy_rule = self.create_policy_rule(
policy_classifier_id=classifier_id, name='pr1', policy_classifier_id=classifier_id,
policy_actions=action_id_list) policy_actions=action_id_list)
policy_rule_id = policy_rule['policy_rule']['id'] policy_rule_id = policy_rule['policy_rule']['id']
policy_rule_list = [policy_rule_id] policy_rule_list = [policy_rule_id]
contract = self.create_contract(name="c1", policy_rule_set = self.create_policy_rule_set(
policy_rules=policy_rule_list) name="c1", policy_rules=policy_rule_list)
contract_id = contract['contract']['id'] policy_rule_set_id = policy_rule_set['policy_rule_set']['id']
self.create_endpoint_group(name="epg1", self.create_policy_target_group(
provided_contracts={contract_id: None}) name="ptg1", provided_policy_rule_sets={policy_rule_set_id: None})
consumed_epg = self.create_endpoint_group(name="epg2", consumed_ptg = self.create_policy_target_group(
consumed_contracts={contract_id: None}) name="ptg2", consumed_policy_rule_sets={policy_rule_set_id: None})
epg_id = consumed_epg['endpoint_group']['id'] ptg_id = consumed_ptg['policy_target_group']['id']
ep = self.create_endpoint(name="ep2", endpoint_group_id=epg_id) pt = self.create_policy_target(
name="pt2", policy_target_group_id=ptg_id)
# verify SG bind to port # verify SG bind to port
port_id = ep['endpoint']['port_id'] port_id = pt['policy_target']['port_id']
res = self.new_show_request('ports', port_id) res = self.new_show_request('ports', port_id)
port = self.deserialize(self.fmt, res.get_response(self.api)) port = self.deserialize(self.fmt, res.get_response(self.api))
security_groups = port['port'][ext_sg.SECURITYGROUPS] security_groups = port['port'][ext_sg.SECURITYGROUPS]
self.assertEqual(len(security_groups), 2) self.assertEqual(len(security_groups), 2)
# Test update and delete of EPG, how it affects SG mapping # Test update and delete of PTG, how it affects SG mapping
def test_endpoint_group_update(self): def test_policy_target_group_update(self):
# create two contracts: bind one to an EPG, update with # create two policy_rule_sets: bind one to an PTG, update with
# adding another one (increase SG count on EP on EPG) # adding another one (increase SG count on PT on PTG)
classifier1 = self.create_policy_classifier(name="class1", classifier1 = self.create_policy_classifier(
protocol="tcp", direction="bi", port_range="30:80") name="class1", protocol="tcp", direction="bi", port_range="30:80")
classifier2 = self.create_policy_classifier(name="class2", classifier2 = self.create_policy_classifier(
protocol="udp", direction="out", port_range="20:30") name="class2", protocol="udp", direction="out", port_range="20:30")
classifier1_id = classifier1['policy_classifier']['id'] classifier1_id = classifier1['policy_classifier']['id']
classifier2_id = classifier2['policy_classifier']['id'] classifier2_id = classifier2['policy_classifier']['id']
action = self.create_policy_action(name="action1", action = self.create_policy_action(name="action1",
action_type=gconst.GP_ACTION_ALLOW) action_type=gconst.GP_ACTION_ALLOW)
action_id = action['policy_action']['id'] action_id = action['policy_action']['id']
action_id_list = [action_id] action_id_list = [action_id]
policy_rule1 = self.create_policy_rule(name='pr1', policy_rule1 = self.create_policy_rule(
policy_classifier_id=classifier1_id, name='pr1', policy_classifier_id=classifier1_id,
policy_actions=action_id_list) policy_actions=action_id_list)
policy_rule2 = self.create_policy_rule(name='pr2', policy_rule2 = self.create_policy_rule(
policy_classifier_id=classifier2_id, name='pr2', policy_classifier_id=classifier2_id,
policy_actions=action_id_list) policy_actions=action_id_list)
policy_rule1_id = policy_rule1['policy_rule']['id'] policy_rule1_id = policy_rule1['policy_rule']['id']
policy_rule1_list = [policy_rule1_id] policy_rule1_list = [policy_rule1_id]
policy_rule2_id = policy_rule2['policy_rule']['id'] policy_rule2_id = policy_rule2['policy_rule']['id']
policy_rule2_list = [policy_rule2_id] policy_rule2_list = [policy_rule2_id]
contract1 = self.create_contract(name="c1", policy_rule_set1 = self.create_policy_rule_set(
policy_rules=policy_rule1_list) name="c1", policy_rules=policy_rule1_list)
contract1_id = contract1['contract']['id'] policy_rule_set1_id = policy_rule_set1['policy_rule_set']['id']
contract2 = self.create_contract(name="c2", policy_rule_set2 = self.create_policy_rule_set(
policy_rules=policy_rule2_list) name="c2", policy_rules=policy_rule2_list)
contract2_id = contract2['contract']['id'] policy_rule_set2_id = policy_rule_set2['policy_rule_set']['id']
epg1 = self.create_endpoint_group(name="epg1", ptg1 = self.create_policy_target_group(
provided_contracts={contract1_id: None}) name="ptg1", provided_policy_rule_sets={policy_rule_set1_id: None})
epg2 = self.create_endpoint_group(name="epg2", ptg2 = self.create_policy_target_group(
consumed_contracts={contract1_id: None}) name="ptg2", consumed_policy_rule_sets={policy_rule_set1_id: None})
epg1_id = epg1['endpoint_group']['id'] ptg1_id = ptg1['policy_target_group']['id']
epg2_id = epg2['endpoint_group']['id'] ptg2_id = ptg2['policy_target_group']['id']
# endpoint ep1 now with epg2 consumes contract1_id # policy_target pt1 now with ptg2 consumes policy_rule_set1_id
ep1 = self.create_endpoint(name="ep1", pt1 = self.create_policy_target(
endpoint_group_id=epg2_id) name="pt1", policy_target_group_id=ptg2_id)
# ep1's port should have 2 SG associated # pt1's port should have 2 SG associated
port_id = ep1['endpoint']['port_id'] port_id = pt1['policy_target']['port_id']
res = self.new_show_request('ports', port_id) res = self.new_show_request('ports', port_id)
port = self.deserialize(self.fmt, res.get_response(self.api)) port = self.deserialize(self.fmt, res.get_response(self.api))
security_groups = port['port'][ext_sg.SECURITYGROUPS] security_groups = port['port'][ext_sg.SECURITYGROUPS]
self.assertEqual(len(security_groups), 2) self.assertEqual(len(security_groups), 2)
# now add a contract to EPG # now add a policy_rule_set to PTG
# First we update contract2 to be provided by consumed_epg # First we update policy_rule_set2 to be provided by consumed_ptg
data = {'endpoint_group': {'provided_contracts': {contract2_id: None}}} data = {'policy_target_group':
req = self.new_update_request('endpoint_groups', data, epg2_id) {'provided_policy_rule_sets': {policy_rule_set2_id: None}}}
req = self.new_update_request('policy_target_groups', data, ptg2_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPOk.code) self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
# set epg1 to provide contract1 and consume contract2 # set ptg1 to provide policy_rule_set1 and consume policy_rule_set2
# contract2 now maps to SG which has epg2's subnet as CIDR on rules # policy_rule_set2 now maps to SG which has ptg2's subnet as CIDR on
data = {'endpoint_group': {'consumed_contracts': {contract2_id: None}}} # rules
req = self.new_update_request('endpoint_groups', data, epg1_id) data = {'policy_target_group':
{'consumed_policy_rule_sets': {policy_rule_set2_id: None}}}
req = self.new_update_request('policy_target_groups', data, ptg1_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPOk.code) self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
port_id = ep1['endpoint']['port_id'] port_id = pt1['policy_target']['port_id']
res = self.new_show_request('ports', port_id) res = self.new_show_request('ports', port_id)
port = self.deserialize(self.fmt, res.get_response(self.api)) port = self.deserialize(self.fmt, res.get_response(self.api))
security_groups = port['port'][ext_sg.SECURITYGROUPS] security_groups = port['port'][ext_sg.SECURITYGROUPS]
self.assertEqual(len(security_groups), 3) self.assertEqual(len(security_groups), 3)
def test_redirect_to_chain(self): def test_redirect_to_chain(self):
classifier = self.create_policy_classifier(name="class1", classifier = self.create_policy_classifier(
protocol="tcp", direction="in", port_range="20:90") name="class1", protocol="tcp", direction="in", port_range="20:90")
classifier_id = classifier['policy_classifier']['id'] classifier_id = classifier['policy_classifier']['id']
action = self.create_policy_action( action = self.create_policy_action(
name="action1", name="action1", action_type=gconst.GP_ACTION_REDIRECT,
action_type=gconst.GP_ACTION_REDIRECT, action_value=uuidutils.generate_uuid())
action_value=uuidutils.generate_uuid())
action_id = action['policy_action']['id'] action_id = action['policy_action']['id']
action_id_list = [action_id] action_id_list = [action_id]
policy_rule = self.create_policy_rule(name='pr1', policy_rule = self.create_policy_rule(
policy_classifier_id=classifier_id, name='pr1', policy_classifier_id=classifier_id,
policy_actions=action_id_list) policy_actions=action_id_list)
policy_rule_id = policy_rule['policy_rule']['id'] policy_rule_id = policy_rule['policy_rule']['id']
policy_rule_list = [policy_rule_id] policy_rule_list = [policy_rule_id]
contract = self.create_contract(name="c1", policy_rule_set = self.create_policy_rule_set(
policy_rules=policy_rule_list) name="c1", policy_rules=policy_rule_list)
contract_id = contract['contract']['id'] policy_rule_set_id = policy_rule_set['policy_rule_set']['id']
sg_ingress_rule = mock.patch.object( sg_ingress_rule = mock.patch.object(
resource_mapping.ResourceMappingDriver, resource_mapping.ResourceMappingDriver, '_sg_ingress_rule')
'_sg_ingress_rule')
sg_ingress_rule = sg_ingress_rule.start() sg_ingress_rule = sg_ingress_rule.start()
params = [{'type': 'ip_single', 'name': 'vip', 'value': 'self_subnet'}] params = [{'type': 'ip_single', 'name': 'vip', 'value': 'self_subnet'}]
nsp = self.create_network_service_policy(network_service_params=params) nsp = self.create_network_service_policy(network_service_params=params)
nsp_id = nsp['network_service_policy']['id'] nsp_id = nsp['network_service_policy']['id']
self.create_endpoint_group(name="epg1", self.create_policy_target_group(
provided_contracts={contract_id: None}, name="ptg1", provided_policy_rule_sets={policy_rule_set_id: None},
network_service_policy_id=nsp_id) network_service_policy_id=nsp_id)
sg_ingress_rule.assert_called_once_with(mock.ANY, mock.ANY, sg_ingress_rule.assert_called_once_with(mock.ANY, mock.ANY,
"tcp", "20:90", mock.ANY, "tcp", "20:90", mock.ANY,
unset=False) unset=False)
create_chain_instance = mock.patch.object( create_chain_instance = mock.patch.object(
servicechain_plugin.ServiceChainPlugin, servicechain_plugin.ServiceChainPlugin,
'create_servicechain_instance') 'create_servicechain_instance')
create_chain_instance = create_chain_instance.start() create_chain_instance = create_chain_instance.start()
chain_instance_id = uuidutils.generate_uuid() chain_instance_id = uuidutils.generate_uuid()
create_chain_instance.return_value = {'id': chain_instance_id} create_chain_instance.return_value = {'id': chain_instance_id}
#TODO(Magesh):Add tests which verifies that provide/consumer EPGs # TODO(Magesh):Add tests which verifies that provide/consumer PTGs
#are set correctly for the SCI # are set correctly for the SCI
with mock.patch.object( with mock.patch.object(
resource_mapping.ResourceMappingDriver, resource_mapping.ResourceMappingDriver,
'_set_rule_servicechain_instance_mapping') as set_rule: '_set_rule_servicechain_instance_mapping') as set_rule:
with mock.patch.object(servicechain_db.ServiceChainDbPlugin, with mock.patch.object(servicechain_db.ServiceChainDbPlugin,
'get_servicechain_spec') as sc_spec_get: 'get_servicechain_spec') as sc_spec_get:
sc_spec_get.return_value = {'servicechain_spec': {}} sc_spec_get.return_value = {'servicechain_spec': {}}
consumer_epg = self.create_endpoint_group(name="epg2", consumer_ptg = self.create_policy_target_group(
consumed_contracts={contract_id: None}) name="ptg2",
consumer_epg_id = consumer_epg['endpoint_group']['id'] consumed_policy_rule_sets={policy_rule_set_id: None})
consumer_ptg_id = consumer_ptg['policy_target_group']['id']
set_rule.assert_called_once_with(mock.ANY, policy_rule_id, set_rule.assert_called_once_with(mock.ANY, policy_rule_id,
chain_instance_id) chain_instance_id)
with mock.patch.object(servicechain_plugin.ServiceChainPlugin, with mock.patch.object(servicechain_plugin.ServiceChainPlugin,
'delete_servicechain_instance'): 'delete_servicechain_instance'):
with mock.patch.object( with mock.patch.object(
resource_mapping.ResourceMappingDriver, resource_mapping.ResourceMappingDriver,
'_get_rule_servicechain_mapping') as get_rule: '_get_rule_servicechain_mapping') as get_rule:
r_sc_map = resource_mapping.RuleServiceChainInstanceMapping() r_sc_map = resource_mapping.RuleServiceChainInstanceMapping()
r_sc_map.rule_id = policy_rule_id r_sc_map.rule_id = policy_rule_id
r_sc_map.servicechain_instance_id = chain_instance_id r_sc_map.servicechain_instance_id = chain_instance_id
get_rule.return_value = r_sc_map get_rule.return_value = r_sc_map
get_chain_inst = mock.patch.object( get_chain_inst = mock.patch.object(
servicechain_db.ServiceChainDbPlugin, servicechain_db.ServiceChainDbPlugin,
'get_servicechain_instance') 'get_servicechain_instance')
get_chain_inst.start() get_chain_inst.start()
get_chain_inst.return_value = { get_chain_inst.return_value = {
"servicechain_instance": { "servicechain_instance": {'id': chain_instance_id}}
'id': chain_instance_id}}
req = self.new_delete_request( req = self.new_delete_request(
'endpoint_groups', 'policy_target_groups', consumer_ptg_id)
consumer_epg_id)
res = req.get_response(self.ext_api) res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)

View File

@ -28,14 +28,14 @@ GP_PLUGIN_BASE_NAME = (
gp.GroupPolicyPluginBase.__module__ + '.' + gp.GroupPolicyPluginBase.__module__ + '.' +
gp.GroupPolicyPluginBase.__name__) gp.GroupPolicyPluginBase.__name__)
GROUPPOLICY_URI = 'grouppolicy' GROUPPOLICY_URI = 'grouppolicy'
ENDPOINTS_URI = GROUPPOLICY_URI + '/' + 'endpoints' POLICY_TARGETS_URI = GROUPPOLICY_URI + '/' + 'policy_targets'
ENDPOINT_GROUPS_URI = GROUPPOLICY_URI + '/' + 'endpoint_groups' POLICY_TARGET_GROUPS_URI = GROUPPOLICY_URI + '/' + 'policy_target_groups'
L2_POLICIES_URI = GROUPPOLICY_URI + '/' + 'l2_policies' L2_POLICIES_URI = GROUPPOLICY_URI + '/' + 'l2_policies'
L3_POLICIES_URI = GROUPPOLICY_URI + '/' + 'l3_policies' L3_POLICIES_URI = GROUPPOLICY_URI + '/' + 'l3_policies'
POLICY_RULES_URI = GROUPPOLICY_URI + '/' + 'policy_rules' POLICY_RULES_URI = GROUPPOLICY_URI + '/' + 'policy_rules'
POLICY_CLASSIFIERS_URI = GROUPPOLICY_URI + '/' + 'policy_classifiers' POLICY_CLASSIFIERS_URI = GROUPPOLICY_URI + '/' + 'policy_classifiers'
POLICY_ACTIONS_URI = GROUPPOLICY_URI + '/' + 'policy_actions' POLICY_ACTIONS_URI = GROUPPOLICY_URI + '/' + 'policy_actions'
CONTRACTS_URI = GROUPPOLICY_URI + '/' + 'contracts' POLICY_RULE_SETS_URI = GROUPPOLICY_URI + '/' + 'policy_rule_sets'
NET_SVC_POLICIES_URI = GROUPPOLICY_URI + '/' + 'network_service_policies' NET_SVC_POLICIES_URI = GROUPPOLICY_URI + '/' + 'network_service_policies'
@ -53,204 +53,210 @@ class GroupPolicyExtensionTestCase(test_api_v2_extension.ExtensionTestCase):
plural_mappings=plural_mappings) plural_mappings=plural_mappings)
self.instance = self.plugin.return_value self.instance = self.plugin.return_value
def _test_create_endpoint(self, data, expected_value, default_data=None): def _test_create_policy_target(self, data, expected_value,
default_data=None):
if not default_data: if not default_data:
default_data = data default_data = data
self.instance.create_endpoint.return_value = expected_value self.instance.create_policy_target.return_value = expected_value
res = self.api.post(_get_path(ENDPOINTS_URI, fmt=self.fmt), res = self.api.post(_get_path(POLICY_TARGETS_URI, fmt=self.fmt),
self.serialize(data), self.serialize(data),
content_type='application/%s' % self.fmt) content_type='application/%s' % self.fmt)
self.instance.create_endpoint.assert_called_once_with( self.instance.create_policy_target.assert_called_once_with(
mock.ANY, endpoint=default_data) mock.ANY, policy_target=default_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int) self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res) res = self.deserialize(res)
self.assertIn('endpoint', res) self.assertIn('policy_target', res)
self.assertEqual(expected_value, res['endpoint']) self.assertEqual(expected_value, res['policy_target'])
def _get_create_endpoint_default_attrs(self): def _get_create_policy_target_default_attrs(self):
return {'name': '', 'description': ''} return {'name': '', 'description': ''}
def _get_create_endpoint_attrs(self): def _get_create_policy_target_attrs(self):
return {'name': 'ep1', 'endpoint_group_id': _uuid(), return {'name': 'ep1', 'policy_target_group_id': _uuid(),
'tenant_id': _uuid(), 'description': 'test endpoint'} 'tenant_id': _uuid(), 'description': 'test policy_target'}
def _get_update_endpoint_attrs(self): def _get_update_policy_target_attrs(self):
return {'name': 'new_name'} return {'name': 'new_name'}
def test_create_endpoint_with_defaults(self): def test_create_policy_target_with_defaults(self):
endpoint_id = _uuid() policy_target_id = _uuid()
data = {'endpoint': {'endpoint_group_id': _uuid(), data = {'policy_target': {'policy_target_group_id': _uuid(),
'tenant_id': _uuid()}} 'tenant_id': _uuid()}}
default_attrs = self._get_create_endpoint_default_attrs() default_attrs = self._get_create_policy_target_default_attrs()
default_data = copy.copy(data) default_data = copy.copy(data)
default_data['endpoint'].update(default_attrs) default_data['policy_target'].update(default_attrs)
expected_value = dict(default_data['endpoint']) expected_value = dict(default_data['policy_target'])
expected_value['id'] = endpoint_id expected_value['id'] = policy_target_id
self._test_create_endpoint(data, expected_value, default_data) self._test_create_policy_target(data, expected_value, default_data)
def test_create_endpoint(self): def test_create_policy_target(self):
endpoint_id = _uuid() policy_target_id = _uuid()
data = {'endpoint': self._get_create_endpoint_attrs()} data = {'policy_target': self._get_create_policy_target_attrs()}
expected_value = dict(data['endpoint']) expected_value = dict(data['policy_target'])
expected_value['id'] = endpoint_id expected_value['id'] = policy_target_id
self._test_create_endpoint(data, expected_value) self._test_create_policy_target(data, expected_value)
def test_list_endpoints(self): def test_list_policy_targets(self):
endpoint_id = _uuid() policy_target_id = _uuid()
expected_value = [{'tenant_id': _uuid(), 'id': endpoint_id}] expected_value = [{'tenant_id': _uuid(), 'id': policy_target_id}]
self.instance.get_endpoints.return_value = expected_value self.instance.get_policy_targets.return_value = expected_value
res = self.api.get(_get_path(ENDPOINTS_URI, fmt=self.fmt)) res = self.api.get(_get_path(POLICY_TARGETS_URI, fmt=self.fmt))
self.instance.get_endpoints.assert_called_once_with( self.instance.get_policy_targets.assert_called_once_with(
mock.ANY, fields=mock.ANY, filters=mock.ANY) mock.ANY, fields=mock.ANY, filters=mock.ANY)
self.assertEqual(exc.HTTPOk.code, res.status_int) self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res) res = self.deserialize(res)
self.assertIn('endpoints', res) self.assertIn('policy_targets', res)
self.assertEqual(expected_value, res['endpoints']) self.assertEqual(expected_value, res['policy_targets'])
def test_get_endpoint(self): def test_get_policy_target(self):
endpoint_id = _uuid() policy_target_id = _uuid()
expected_value = {'tenant_id': _uuid(), 'id': endpoint_id} expected_value = {'tenant_id': _uuid(), 'id': policy_target_id}
self.instance.get_endpoint.return_value = expected_value self.instance.get_policy_target.return_value = expected_value
res = self.api.get(_get_path(ENDPOINTS_URI, id=endpoint_id, res = self.api.get(_get_path(POLICY_TARGETS_URI, id=policy_target_id,
fmt=self.fmt)) fmt=self.fmt))
self.instance.get_endpoint.assert_called_once_with( self.instance.get_policy_target.assert_called_once_with(
mock.ANY, endpoint_id, fields=mock.ANY) mock.ANY, policy_target_id, fields=mock.ANY)
self.assertEqual(exc.HTTPOk.code, res.status_int) self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res) res = self.deserialize(res)
self.assertIn('endpoint', res) self.assertIn('policy_target', res)
self.assertEqual(expected_value, res['endpoint']) self.assertEqual(expected_value, res['policy_target'])
def test_update_endpoint(self): def test_update_policy_target(self):
endpoint_id = _uuid() policy_target_id = _uuid()
update_data = {'endpoint': self._get_update_endpoint_attrs()} update_data = {'policy_target': self._get_update_policy_target_attrs()}
expected_value = {'tenant_id': _uuid(), 'id': endpoint_id} expected_value = {'tenant_id': _uuid(), 'id': policy_target_id}
self.instance.update_endpoint.return_value = expected_value self.instance.update_policy_target.return_value = expected_value
res = self.api.put(_get_path(ENDPOINTS_URI, id=endpoint_id, res = self.api.put(_get_path(POLICY_TARGETS_URI, id=policy_target_id,
fmt=self.fmt), fmt=self.fmt),
self.serialize(update_data)) self.serialize(update_data))
self.instance.update_endpoint.assert_called_once_with( self.instance.update_policy_target.assert_called_once_with(
mock.ANY, endpoint_id, endpoint=update_data) mock.ANY, policy_target_id, policy_target=update_data)
self.assertEqual(exc.HTTPOk.code, res.status_int) self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res) res = self.deserialize(res)
self.assertIn('endpoint', res) self.assertIn('policy_target', res)
self.assertEqual(expected_value, res['endpoint']) self.assertEqual(expected_value, res['policy_target'])
def test_delete_endpoint(self): def test_delete_policy_target(self):
self._test_entity_delete('endpoint') self._test_entity_delete('policy_target')
def _test_create_endpoint_group(self, data, expected_value, def _test_create_policy_target_group(self, data, expected_value,
default_data=None): default_data=None):
if not default_data: if not default_data:
default_data = data default_data = data
self.instance.create_endpoint_group.return_value = expected_value self.instance.create_policy_target_group.return_value = expected_value
res = self.api.post(_get_path(ENDPOINT_GROUPS_URI, fmt=self.fmt), res = self.api.post(_get_path(POLICY_TARGET_GROUPS_URI, fmt=self.fmt),
self.serialize(data), self.serialize(data),
content_type='application/%s' % self.fmt) content_type='application/%s' % self.fmt)
self.instance.create_endpoint_group.assert_called_once_with( self.instance.create_policy_target_group.assert_called_once_with(
mock.ANY, endpoint_group=default_data) mock.ANY, policy_target_group=default_data)
self.assertEqual(exc.HTTPCreated.code, res.status_int) self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res) res = self.deserialize(res)
self.assertIn('endpoint_group', res) self.assertIn('policy_target_group', res)
self.assertEqual(expected_value, res['endpoint_group']) self.assertEqual(expected_value, res['policy_target_group'])
def _get_create_endpoint_group_default_attrs(self): def _get_create_policy_target_group_default_attrs(self):
return {'name': '', 'description': '', 'l2_policy_id': None, return {'name': '', 'description': '', 'l2_policy_id': None,
'provided_contracts': {}, 'consumed_contracts': {}, 'provided_policy_rule_sets': {},
'consumed_policy_rule_sets': {},
'network_service_policy_id': None} 'network_service_policy_id': None}
def _get_create_endpoint_group_attrs(self): def _get_create_policy_target_group_attrs(self):
return {'name': 'epg1', 'tenant_id': _uuid(), return {'name': 'ptg1', 'tenant_id': _uuid(),
'description': 'test endpoint group', 'l2_policy_id': _uuid(), 'description': 'test policy_target group',
'provided_contracts': {_uuid(): None}, 'l2_policy_id': _uuid(),
'consumed_contracts': {_uuid(): None}, 'provided_policy_rule_sets': {_uuid(): None},
'consumed_policy_rule_sets': {_uuid(): None},
'network_service_policy_id': _uuid()} 'network_service_policy_id': _uuid()}
def _get_update_endpoint_group_attrs(self): def _get_update_policy_target_group_attrs(self):
return {'name': 'new_name'} return {'name': 'new_name'}
def test_create_endpoint_group_with_defaults(self): def test_create_policy_target_group_with_defaults(self):
endpoint_group_id = _uuid() policy_target_group_id = _uuid()
data = {'endpoint_group': {'tenant_id': _uuid()}} data = {'policy_target_group': {'tenant_id': _uuid()}}
default_attrs = self._get_create_endpoint_group_default_attrs() default_attrs = self._get_create_policy_target_group_default_attrs()
default_data = copy.copy(data) default_data = copy.copy(data)
default_data['endpoint_group'].update(default_attrs) default_data['policy_target_group'].update(default_attrs)
expected_value = copy.deepcopy(default_data['endpoint_group']) expected_value = copy.deepcopy(default_data['policy_target_group'])
expected_value['id'] = endpoint_group_id expected_value['id'] = policy_target_group_id
self._test_create_endpoint_group(data, expected_value, default_data) self._test_create_policy_target_group(data, expected_value,
default_data)
def test_create_endpoint_group(self): def test_create_policy_target_group(self):
endpoint_group_id = _uuid() policy_target_group_id = _uuid()
data = {'endpoint_group': self._get_create_endpoint_group_attrs()} data = {'policy_target_group':
expected_value = copy.deepcopy(data['endpoint_group']) self._get_create_policy_target_group_attrs()}
expected_value['id'] = endpoint_group_id expected_value = copy.deepcopy(data['policy_target_group'])
expected_value['id'] = policy_target_group_id
self._test_create_endpoint_group(data, expected_value) self._test_create_policy_target_group(data, expected_value)
def test_list_endpoint_groups(self): def test_list_policy_target_groups(self):
endpoint_group_id = _uuid() policy_target_group_id = _uuid()
expected_value = [{'tenant_id': _uuid(), 'id': endpoint_group_id}] expected_value = [{'tenant_id': _uuid(), 'id': policy_target_group_id}]
self.instance.get_endpoint_groups.return_value = expected_value self.instance.get_policy_target_groups.return_value = expected_value
res = self.api.get(_get_path(ENDPOINT_GROUPS_URI, fmt=self.fmt)) res = self.api.get(_get_path(POLICY_TARGET_GROUPS_URI, fmt=self.fmt))
self.instance.get_endpoint_groups.assert_called_once_with( self.instance.get_policy_target_groups.assert_called_once_with(
mock.ANY, fields=mock.ANY, filters=mock.ANY) mock.ANY, fields=mock.ANY, filters=mock.ANY)
self.assertEqual(exc.HTTPOk.code, res.status_int) self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res) res = self.deserialize(res)
self.assertIn('endpoint_groups', res) self.assertIn('policy_target_groups', res)
self.assertEqual(expected_value, res['endpoint_groups']) self.assertEqual(expected_value, res['policy_target_groups'])
def test_get_endpoint_group(self): def test_get_policy_target_group(self):
endpoint_group_id = _uuid() policy_target_group_id = _uuid()
expected_value = {'tenant_id': _uuid(), 'id': endpoint_group_id} expected_value = {'tenant_id': _uuid(), 'id': policy_target_group_id}
self.instance.get_endpoint_group.return_value = expected_value self.instance.get_policy_target_group.return_value = expected_value
res = self.api.get(_get_path(ENDPOINT_GROUPS_URI, id=endpoint_group_id, res = self.api.get(_get_path(POLICY_TARGET_GROUPS_URI,
id=policy_target_group_id,
fmt=self.fmt)) fmt=self.fmt))
self.instance.get_endpoint_group.assert_called_once_with( self.instance.get_policy_target_group.assert_called_once_with(
mock.ANY, endpoint_group_id, fields=mock.ANY) mock.ANY, policy_target_group_id, fields=mock.ANY)
self.assertEqual(exc.HTTPOk.code, res.status_int) self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res) res = self.deserialize(res)
self.assertIn('endpoint_group', res) self.assertIn('policy_target_group', res)
self.assertEqual(expected_value, res['endpoint_group']) self.assertEqual(expected_value, res['policy_target_group'])
def test_update_endpoint_group(self): def test_update_policy_target_group(self):
endpoint_group_id = _uuid() policy_target_group_id = _uuid()
update_data = {'endpoint_group': update_data = {'policy_target_group':
self._get_update_endpoint_group_attrs()} self._get_update_policy_target_group_attrs()}
expected_value = {'tenant_id': _uuid(), 'id': endpoint_group_id} expected_value = {'tenant_id': _uuid(), 'id': policy_target_group_id}
self.instance.update_endpoint_group.return_value = expected_value self.instance.update_policy_target_group.return_value = expected_value
res = self.api.put(_get_path(ENDPOINT_GROUPS_URI, res = self.api.put(_get_path(POLICY_TARGET_GROUPS_URI,
id=endpoint_group_id, fmt=self.fmt), id=policy_target_group_id, fmt=self.fmt),
self.serialize(update_data)) self.serialize(update_data))
self.instance.update_endpoint_group.assert_called_once_with( self.instance.update_policy_target_group.assert_called_once_with(
mock.ANY, endpoint_group_id, endpoint_group=update_data) mock.ANY, policy_target_group_id, policy_target_group=update_data)
self.assertEqual(exc.HTTPOk.code, res.status_int) self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res) res = self.deserialize(res)
self.assertIn('endpoint_group', res) self.assertIn('policy_target_group', res)
self.assertEqual(expected_value, res['endpoint_group']) self.assertEqual(expected_value, res['policy_target_group'])
def test_delete_endpoint_group(self): def test_delete_policy_target_group(self):
self._test_entity_delete('endpoint_group') self._test_entity_delete('policy_target_group')
def _test_create_l2_policy(self, data, expected_value, default_data=None): def _test_create_l2_policy(self, data, expected_value, default_data=None):
if not default_data: if not default_data:
@ -619,11 +625,8 @@ class GroupPolicyExtensionTestCase(test_api_v2_extension.ExtensionTestCase):
res = self.api.get(_get_path(POLICY_CLASSIFIERS_URI, fmt=self.fmt)) res = self.api.get(_get_path(POLICY_CLASSIFIERS_URI, fmt=self.fmt))
instance.get_policy_classifiers.assert_called_once_with(mock.ANY, instance.get_policy_classifiers.assert_called_once_with(
fields= mock.ANY, fields=mock.ANY, filters=mock.ANY)
mock.ANY,
filters=
mock.ANY)
self.assertEqual(res.status_int, exc.HTTPOk.code) self.assertEqual(res.status_int, exc.HTTPOk.code)
def test_get_policy_classifier(self): def test_get_policy_classifier(self):
@ -781,113 +784,114 @@ class GroupPolicyExtensionTestCase(test_api_v2_extension.ExtensionTestCase):
def test_delete_policy_rule(self): def test_delete_policy_rule(self):
self._test_entity_delete('policy_action') self._test_entity_delete('policy_action')
def _test_create_contract(self, data, expected_value, default_data=None): def _test_create_policy_rule_set(self, data, expected_value,
default_data=None):
if not default_data: if not default_data:
default_data = data default_data = data
self.instance.create_contract.return_value = expected_value self.instance.create_policy_rule_set.return_value = expected_value
res = self.api.post(_get_path(CONTRACTS_URI, fmt=self.fmt), res = self.api.post(_get_path(POLICY_RULE_SETS_URI, fmt=self.fmt),
self.serialize(data), self.serialize(data),
content_type='application/%s' % self.fmt) content_type='application/%s' % self.fmt)
self.instance.create_contract.assert_called_once_with( self.instance.create_policy_rule_set.assert_called_once_with(
mock.ANY, contract=default_data) mock.ANY, policy_rule_set=default_data)
self.assertEqual(res.status_int, exc.HTTPCreated.code) self.assertEqual(res.status_int, exc.HTTPCreated.code)
res = self.deserialize(res) res = self.deserialize(res)
self.assertIn('contract', res) self.assertIn('policy_rule_set', res)
self.assertEqual(expected_value, res['contract']) self.assertEqual(expected_value, res['policy_rule_set'])
def _get_create_contract_default_attrs(self): def _get_create_policy_rule_set_default_attrs(self):
return {'name': '', return {'name': '',
'description': '', 'description': '',
'child_contracts': [], 'child_policy_rule_sets': [],
'policy_rules': []} 'policy_rules': []}
def _get_create_contract_attrs(self): def _get_create_policy_rule_set_attrs(self):
return {'name': 'contract1', return {'name': 'policy_rule_set1',
'description': 'test contract', 'description': 'test policy_rule_set',
'tenant_id': _uuid(), 'tenant_id': _uuid(),
'child_contracts': [_uuid()], 'child_policy_rule_sets': [_uuid()],
'policy_rules': [_uuid()]} 'policy_rules': [_uuid()]}
def _get_update_contract_attrs(self): def _get_update_policy_rule_set_attrs(self):
return {'name': 'new_name'} return {'name': 'new_name'}
def test_create_contract_with_defaults(self): def test_create_policy_rule_set_with_defaults(self):
contract_id = _uuid() policy_rule_set_id = _uuid()
data = {'contract': {'tenant_id': _uuid()}} data = {'policy_rule_set': {'tenant_id': _uuid()}}
default_attrs = self._get_create_contract_default_attrs() default_attrs = self._get_create_policy_rule_set_default_attrs()
default_data = copy.copy(data) default_data = copy.copy(data)
default_data['contract'].update(default_attrs) default_data['policy_rule_set'].update(default_attrs)
expected_value = dict(default_data['contract']) expected_value = dict(default_data['policy_rule_set'])
expected_value['id'] = contract_id expected_value['id'] = policy_rule_set_id
self._test_create_contract(data, expected_value, default_data) self._test_create_policy_rule_set(data, expected_value, default_data)
def test_create_contract(self): def test_create_policy_rule_set(self):
contract_id = _uuid() policy_rule_set_id = _uuid()
data = {'contract': data = {'policy_rule_set':
self._get_create_contract_attrs()} self._get_create_policy_rule_set_attrs()}
expected_value = dict(data['contract']) expected_value = dict(data['policy_rule_set'])
expected_value['id'] = contract_id expected_value['id'] = policy_rule_set_id
self._test_create_contract(data, expected_value) self._test_create_policy_rule_set(data, expected_value)
def test_list_contracts(self): def test_list_policy_rule_sets(self):
contract_id = _uuid() policy_rule_set_id = _uuid()
expected_value = [{'tenant_id': _uuid(), expected_value = [{'tenant_id': _uuid(),
'id': contract_id}] 'id': policy_rule_set_id}]
instance = self.plugin.return_value instance = self.plugin.return_value
instance.get_contracts.return_value = expected_value instance.get_policy_rule_sets.return_value = expected_value
res = self.api.get(_get_path(CONTRACTS_URI, fmt=self.fmt)) res = self.api.get(_get_path(POLICY_RULE_SETS_URI, fmt=self.fmt))
instance.get_contracts.assert_called_once_with(mock.ANY, instance.get_policy_rule_sets.assert_called_once_with(
fields=mock.ANY, mock.ANY, fields=mock.ANY, filters=mock.ANY)
filters=mock.ANY)
self.assertEqual(res.status_int, exc.HTTPOk.code) self.assertEqual(res.status_int, exc.HTTPOk.code)
def test_get_contract(self): def test_get_policy_rule_set(self):
contract_id = _uuid() policy_rule_set_id = _uuid()
expected_value = {'tenant_id': _uuid(), expected_value = {'tenant_id': _uuid(),
'id': contract_id} 'id': policy_rule_set_id}
instance = self.plugin.return_value instance = self.plugin.return_value
instance.get_contract.return_value = expected_value instance.get_policy_rule_set.return_value = expected_value
res = self.api.get(_get_path(CONTRACTS_URI, res = self.api.get(_get_path(POLICY_RULE_SETS_URI,
id=contract_id, fmt=self.fmt)) id=policy_rule_set_id, fmt=self.fmt))
instance.get_contract.assert_called_once_with( instance.get_policy_rule_set.assert_called_once_with(
mock.ANY, contract_id, fields=mock.ANY) mock.ANY, policy_rule_set_id, fields=mock.ANY)
self.assertEqual(res.status_int, exc.HTTPOk.code) self.assertEqual(res.status_int, exc.HTTPOk.code)
res = self.deserialize(res) res = self.deserialize(res)
self.assertIn('contract', res) self.assertIn('policy_rule_set', res)
self.assertEqual(expected_value, res['contract']) self.assertEqual(expected_value, res['policy_rule_set'])
def test_update_contract(self): def test_update_policy_rule_set(self):
contract_id = _uuid() policy_rule_set_id = _uuid()
update_data = {'contract': update_data = {'policy_rule_set':
self._get_update_contract_attrs()} self._get_update_policy_rule_set_attrs()}
expected_value = {'tenant_id': _uuid(), expected_value = {'tenant_id': _uuid(),
'id': contract_id} 'id': policy_rule_set_id}
instance = self.plugin.return_value instance = self.plugin.return_value
instance.update_contract.return_value = expected_value instance.update_policy_rule_set.return_value = expected_value
res = self.api.put(_get_path(CONTRACTS_URI, id=contract_id, res = self.api.put(_get_path(POLICY_RULE_SETS_URI,
id=policy_rule_set_id,
fmt=self.fmt), fmt=self.fmt),
self.serialize(update_data)) self.serialize(update_data))
instance.update_contract.assert_called_once_with( instance.update_policy_rule_set.assert_called_once_with(
mock.ANY, contract_id, contract=update_data) mock.ANY, policy_rule_set_id, policy_rule_set=update_data)
self.assertEqual(res.status_int, exc.HTTPOk.code) self.assertEqual(res.status_int, exc.HTTPOk.code)
res = self.deserialize(res) res = self.deserialize(res)
self.assertIn('contract', res) self.assertIn('policy_rule_set', res)
self.assertEqual(expected_value, res['contract']) self.assertEqual(expected_value, res['policy_rule_set'])
def test_delete_contract(self): def test_delete_policy_rule_set(self):
self._test_entity_delete('contract') self._test_entity_delete('policy_rule_set')
def _test_create_network_service_policy( def _test_create_network_service_policy(
self, data, expected_value, default_data=None): self, data, expected_value, default_data=None):

View File

@ -27,10 +27,10 @@ class GroupPolicyMappingExtTestCase(tgp.GroupPolicyExtensionTestCase):
super(tgp.GroupPolicyExtensionTestCase, self).setUp() super(tgp.GroupPolicyExtensionTestCase, self).setUp()
attr_map = gp.RESOURCE_ATTRIBUTE_MAP attr_map = gp.RESOURCE_ATTRIBUTE_MAP
attr_map[gp.ENDPOINTS].update( attr_map[gp.POLICY_TARGETS].update(
gpm.EXTENDED_ATTRIBUTES_2_0[gp.ENDPOINTS]) gpm.EXTENDED_ATTRIBUTES_2_0[gp.POLICY_TARGETS])
attr_map[gp.ENDPOINT_GROUPS].update( attr_map[gp.POLICY_TARGET_GROUPS].update(
gpm.EXTENDED_ATTRIBUTES_2_0[gp.ENDPOINT_GROUPS]) gpm.EXTENDED_ATTRIBUTES_2_0[gp.POLICY_TARGET_GROUPS])
attr_map[gp.L2_POLICIES].update( attr_map[gp.L2_POLICIES].update(
gpm.EXTENDED_ATTRIBUTES_2_0[gp.L2_POLICIES]) gpm.EXTENDED_ATTRIBUTES_2_0[gp.L2_POLICIES])
attr_map[gp.L3_POLICIES].update( attr_map[gp.L3_POLICIES].update(
@ -48,33 +48,33 @@ class GroupPolicyMappingExtTestCase(tgp.GroupPolicyExtensionTestCase):
def _restore_gp_attr_map(self): def _restore_gp_attr_map(self):
gp.RESOURCE_ATTRIBUTE_MAP = self._saved_gp_attr_map gp.RESOURCE_ATTRIBUTE_MAP = self._saved_gp_attr_map
def _get_create_endpoint_default_attrs(self): def _get_create_policy_target_default_attrs(self):
attrs = (super(GroupPolicyMappingExtTestCase, self). attrs = (super(GroupPolicyMappingExtTestCase, self).
_get_create_endpoint_default_attrs()) _get_create_policy_target_default_attrs())
attrs.update({'port_id': None}) attrs.update({'port_id': None})
return attrs return attrs
def _get_create_endpoint_attrs(self): def _get_create_policy_target_attrs(self):
attrs = (super(GroupPolicyMappingExtTestCase, self). attrs = (super(GroupPolicyMappingExtTestCase, self).
_get_create_endpoint_attrs()) _get_create_policy_target_attrs())
attrs.update({'port_id': tgp._uuid()}) attrs.update({'port_id': tgp._uuid()})
return attrs return attrs
def _get_create_endpoint_group_default_attrs(self): def _get_create_policy_target_group_default_attrs(self):
attrs = (super(GroupPolicyMappingExtTestCase, self). attrs = (super(GroupPolicyMappingExtTestCase, self).
_get_create_endpoint_group_default_attrs()) _get_create_policy_target_group_default_attrs())
attrs.update({'subnets': []}) attrs.update({'subnets': []})
return attrs return attrs
def _get_create_endpoint_group_attrs(self): def _get_create_policy_target_group_attrs(self):
attrs = (super(GroupPolicyMappingExtTestCase, self). attrs = (super(GroupPolicyMappingExtTestCase, self).
_get_create_endpoint_group_attrs()) _get_create_policy_target_group_attrs())
attrs.update({'subnets': [tgp._uuid()]}) attrs.update({'subnets': [tgp._uuid()]})
return attrs return attrs
def _get_update_endpoint_group_attrs(self): def _get_update_policy_target_group_attrs(self):
attrs = (super(GroupPolicyMappingExtTestCase, self). attrs = (super(GroupPolicyMappingExtTestCase, self).
_get_update_endpoint_group_attrs()) _get_update_policy_target_group_attrs())
attrs.update({'subnets': [tgp._uuid()]}) attrs.update({'subnets': [tgp._uuid()]})
return attrs return attrs

View File

@ -87,9 +87,9 @@ class ServiceChainExtensionTestCase(test_api_v2_extension.ExtensionTestCase):
servicechain_node_id = _uuid() servicechain_node_id = _uuid()
data = { data = {
'servicechain_node': { 'servicechain_node': {
'service_type': 'FIREWALL', 'service_type': 'FIREWALL',
'tenant_id': _uuid(), 'tenant_id': _uuid(),
'config': 'test_config' 'config': 'test_config'
} }
} }
default_attrs = self._get_create_servicechain_node_default_attrs() default_attrs = self._get_create_servicechain_node_default_attrs()
@ -127,8 +127,7 @@ class ServiceChainExtensionTestCase(test_api_v2_extension.ExtensionTestCase):
def test_get_servicechain_node(self): def test_get_servicechain_node(self):
servicechain_node_id = _uuid() servicechain_node_id = _uuid()
expected_value = { expected_value = {
'tenant_id': _uuid(), 'id': servicechain_node_id 'tenant_id': _uuid(), 'id': servicechain_node_id}
}
self.instance.get_servicechain_node.return_value = expected_value self.instance.get_servicechain_node.return_value = expected_value
res = self.api.get(_get_path(SERVICECHAIN_NODES_URI, res = self.api.get(_get_path(SERVICECHAIN_NODES_URI,
@ -207,8 +206,7 @@ class ServiceChainExtensionTestCase(test_api_v2_extension.ExtensionTestCase):
servicechain_spec_id = _uuid() servicechain_spec_id = _uuid()
data = { data = {
'servicechain_spec': { 'servicechain_spec': {
'nodes': [_uuid(), _uuid()], 'nodes': [_uuid(), _uuid()], 'tenant_id': _uuid()
'tenant_id': _uuid()
} }
} }
default_attrs = self._get_create_servicechain_spec_default_attrs() default_attrs = self._get_create_servicechain_spec_default_attrs()
@ -287,7 +285,7 @@ class ServiceChainExtensionTestCase(test_api_v2_extension.ExtensionTestCase):
if not default_data: if not default_data:
default_data = data default_data = data
self.instance.create_servicechain_instance.return_value = ( self.instance.create_servicechain_instance.return_value = (
expected_value) expected_value)
res = self.api.post(_get_path(SERVICECHAIN_INSTANCES_URI, res = self.api.post(_get_path(SERVICECHAIN_INSTANCES_URI,
fmt=self.fmt), fmt=self.fmt),
self.serialize(data), self.serialize(data),
@ -308,8 +306,8 @@ class ServiceChainExtensionTestCase(test_api_v2_extension.ExtensionTestCase):
'name': 'servicechaininstance1', 'name': 'servicechaininstance1',
'servicechain_spec': _uuid(), 'servicechain_spec': _uuid(),
'tenant_id': _uuid(), 'tenant_id': _uuid(),
'provider_epg': _uuid(), 'provider_ptg': _uuid(),
'consumer_epg': _uuid(), 'consumer_ptg': _uuid(),
'classifier': _uuid(), 'classifier': _uuid(),
'config_param_values': "{}", 'config_param_values': "{}",
'description': 'test servicechain instance' 'description': 'test servicechain instance'
@ -325,12 +323,12 @@ class ServiceChainExtensionTestCase(test_api_v2_extension.ExtensionTestCase):
servicechain_instance_id = _uuid() servicechain_instance_id = _uuid()
data = { data = {
'servicechain_instance': { 'servicechain_instance': {
'servicechain_spec': _uuid(), 'servicechain_spec': _uuid(),
'tenant_id': _uuid(), 'tenant_id': _uuid(),
'provider_epg': _uuid(), 'provider_ptg': _uuid(),
'consumer_epg': _uuid(), 'consumer_ptg': _uuid(),
'classifier': _uuid() 'classifier': _uuid()
} }
} }
default_attrs = self._get_create_servicechain_instance_default_attrs() default_attrs = self._get_create_servicechain_instance_default_attrs()
default_data = copy.copy(data) default_data = copy.copy(data)
@ -387,7 +385,7 @@ class ServiceChainExtensionTestCase(test_api_v2_extension.ExtensionTestCase):
self._get_update_servicechain_instance_attrs()} self._get_update_servicechain_instance_attrs()}
expected_value = {'tenant_id': _uuid(), 'id': servicechain_instance_id} expected_value = {'tenant_id': _uuid(), 'id': servicechain_instance_id}
self.instance.update_servicechain_instance.return_value = ( self.instance.update_servicechain_instance.return_value = (
expected_value) expected_value)
res = self.api.put(_get_path(SERVICECHAIN_INSTANCES_URI, res = self.api.put(_get_path(SERVICECHAIN_INSTANCES_URI,
id=servicechain_instance_id, id=servicechain_instance_id,