2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow;
11 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.addNxRegMatch;
12 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.applyActionIns;
13 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.instructions;
14 import static org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.nxOutputRegAction;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.Comparator;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
25 import javax.annotation.concurrent.Immutable;
27 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.OfContext;
28 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.PolicyManager.FlowMap;
29 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils.RegMatch;
30 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.OrdinalFactory.EndpointFwdCtxOrdinals;
31 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf.Action;
32 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf.AllowAction;
33 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf.ClassificationResult;
34 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf.Classifier;
35 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf.ParamDerivator;
36 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf.SubjectFeatures;
37 import org.opendaylight.groupbasedpolicy.resolver.ConditionGroup;
38 import org.opendaylight.groupbasedpolicy.resolver.EgKey;
39 import org.opendaylight.groupbasedpolicy.resolver.IndexedTenant;
40 import org.opendaylight.groupbasedpolicy.resolver.Policy;
41 import org.opendaylight.groupbasedpolicy.resolver.PolicyInfo;
42 import org.opendaylight.groupbasedpolicy.resolver.RuleGroup;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierDefinitionId;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ConditionName;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection.Direction;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.action.refs.ActionRef;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.classifier.refs.ClassifierRef;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.subject.feature.instance.ParameterValue;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.EndpointGroup;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.EndpointGroup.IntraGroupPolicy;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.contract.subject.Rule;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.subject.feature.instances.ActionInstance;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.subject.feature.instances.ClassifierInstance;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg0;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg1;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg2;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg3;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg5;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg7;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
73 import com.google.common.collect.ComparisonChain;
74 import com.google.common.collect.Ordering;
77 * Manage the table that enforces policy on the traffic. Traffic is denied
78 * unless specifically allowed by policy
80 public class PolicyEnforcer extends FlowTable {
82 protected static final Logger LOG = LoggerFactory.getLogger(PolicyEnforcer.class);
84 public static final short TABLE_ID = 3;
86 public PolicyEnforcer(OfContext ctx) {
91 public short getTableId() {
96 public void sync(NodeId nodeId, PolicyInfo policyInfo, FlowMap flowMap) throws Exception {
98 flowMap.writeFlow(nodeId, TABLE_ID, dropFlow(Integer.valueOf(1), null));
100 NodeConnectorId tunPort = ctx.getSwitchManager().getTunnelPort(nodeId);
101 if (tunPort != null) {
102 flowMap.writeFlow(nodeId, TABLE_ID, allowFromTunnel(tunPort));
105 HashSet<CgPair> visitedPairs = new HashSet<>();
107 // Used for ARP flows
108 Set<Integer> fdIds = new HashSet<>();
110 for (Endpoint srcEp : ctx.getEndpointManager().getEndpointsForNode(nodeId)) {
111 for (EgKey srcEpgKey : ctx.getEndpointManager().getEgKeysForEndpoint(srcEp)) {
112 Set<EgKey> peers = policyInfo.getPeers(srcEpgKey);
113 for (EgKey dstEpgKey : peers) {
114 for (Endpoint dstEp : ctx.getEndpointManager().getEndpointsForGroup(dstEpgKey)) {
116 EndpointFwdCtxOrdinals srcEpFwdCxtOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx,
118 EndpointFwdCtxOrdinals dstEpFwdCxtOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx,
120 int dcgId = dstEpFwdCxtOrds.getCgId();
121 int depgId = dstEpFwdCxtOrds.getEpgId();
122 int scgId = srcEpFwdCxtOrds.getCgId();
123 int sepgId = srcEpFwdCxtOrds.getEpgId();
125 fdIds.add(srcEpFwdCxtOrds.getFdId());
127 List<ConditionName> conds = ctx.getEndpointManager().getCondsForEndpoint(srcEp);
128 ConditionGroup scg = policyInfo.getEgCondGroup(srcEpgKey, conds);
129 conds = ctx.getEndpointManager().getCondsForEndpoint(dstEp);
130 ConditionGroup dcg = policyInfo.getEgCondGroup(dstEpgKey, conds);
132 Policy policy = policyInfo.getPolicy(dstEpgKey, srcEpgKey);
133 List<RuleGroup> rgs = policy.getRules(dcg, scg);
134 CgPair p = new CgPair(depgId, sepgId, dcgId, scgId);
135 if (visitedPairs.contains(p))
138 syncPolicy(flowMap, nodeId, rgs, p);
141 policy = policyInfo.getPolicy(srcEpgKey, dstEpgKey);
142 rgs = policy.getRules(scg, dcg);
143 p = new CgPair(sepgId, depgId, scgId, dcgId);
144 if (visitedPairs.contains(p))
147 syncPolicy(flowMap, nodeId, rgs, p);
154 // Set<Endpoint> visitedEps = new HashSet<>();
155 for (Endpoint srcEp : ctx.getEndpointManager().getEndpointsForNode(nodeId)) {
156 // visitedEps.add(srcEp);
157 for (EgKey srcEpgKey : ctx.getEndpointManager().getEgKeysForEndpoint(srcEp)) {
159 IndexedTenant tenant = ctx.getPolicyResolver().getTenant(srcEpgKey.getTenantId());
160 EndpointGroup group = tenant.getEndpointGroup(srcEpgKey.getEgId());
161 IntraGroupPolicy igp = group.getIntraGroupPolicy();
163 if (igp == null || igp.equals(IntraGroupPolicy.Allow)) {
164 for (Endpoint dstEp : ctx.getEndpointManager().getEndpointsForGroup(srcEpgKey)) {
166 // if(visitedEps.contains(dstEp)) {
169 // visitedEps.add(dstEp);
170 EndpointFwdCtxOrdinals srcEpFwdCxtOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx,
172 EndpointFwdCtxOrdinals dstEpFwdCxtOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx,
174 int depgId = dstEpFwdCxtOrds.getEpgId();
175 int sepgId = srcEpFwdCxtOrds.getEpgId();
176 flowMap.writeFlow(nodeId, TABLE_ID, allowSameEpg(sepgId, depgId));
177 flowMap.writeFlow(nodeId, TABLE_ID, allowSameEpg(depgId, sepgId));
183 // Write ARP flows per flood domain.
184 for (Integer fdId : fdIds) {
185 flowMap.writeFlow(nodeId, TABLE_ID, createArpFlow(fdId));
189 private Flow createArpFlow(Integer fdId) {
191 Long etherType = FlowUtils.ARP;
192 // L2 Classifier so 20,000 for now
193 Integer priority = 20000;
194 FlowId flowid = new FlowId(new StringBuilder().append("arp")
201 MatchBuilder mb = new MatchBuilder().setEthernetMatch(FlowUtils.ethernetMatch(null, null, etherType));
203 addNxRegMatch(mb, RegMatch.of(NxmNxReg5.class, Long.valueOf(fdId)));
205 Flow flow = base().setPriority(priority)
207 .setMatch(mb.build())
208 .setInstructions(instructions(applyActionIns(nxOutputRegAction(NxmNxReg7.class))))
213 private Flow allowSameEpg(int sepgId, int depgId) {
215 FlowId flowId = new FlowId(new StringBuilder().append("intraallow|").append(sepgId).toString());
216 MatchBuilder mb = new MatchBuilder();
217 addNxRegMatch(mb, RegMatch.of(NxmNxReg0.class, Long.valueOf(sepgId)),
218 RegMatch.of(NxmNxReg2.class, Long.valueOf(depgId)));
219 FlowBuilder flow = base().setId(flowId)
220 .setMatch(mb.build())
222 .setInstructions(instructions(applyActionIns(nxOutputRegAction(NxmNxReg7.class))));
226 private Flow allowFromTunnel(NodeConnectorId tunPort) {
228 FlowId flowId = new FlowId("tunnelallow");
229 MatchBuilder mb = new MatchBuilder().setInPort(tunPort);
230 addNxRegMatch(mb, RegMatch.of(NxmNxReg1.class, Long.valueOf(0xffffff)));
231 FlowBuilder flow = base().setId(flowId)
232 .setMatch(mb.build())
234 .setInstructions(instructions(applyActionIns(nxOutputRegAction(NxmNxReg7.class))));
239 private void syncPolicy(FlowMap flowMap, NodeId nodeId, List<RuleGroup> rgs, CgPair p) {
240 int priority = 65000;
241 for (RuleGroup rg : rgs) {
242 TenantId tenantId = rg.getContractTenant().getId();
243 IndexedTenant tenant = ctx.getPolicyResolver().getTenant(tenantId);
244 for (Rule r : rg.getRules()) {
245 syncDirection(flowMap, nodeId, tenant, p, r, Direction.In, priority);
246 syncDirection(flowMap, nodeId, tenant, p, r, Direction.Out, priority);
254 * Private internal class for ordering Actions in Rules. The order is
255 * determined first by the value of the order parameter, with the lower
256 * order actions being applied first; for Actions with either the same order
257 * or no order, ordering is lexicographical by name.
259 private static class ActionRefComparator implements Comparator<ActionRef> {
261 public static final ActionRefComparator INSTANCE = new ActionRefComparator();
264 public int compare(ActionRef arg0, ActionRef arg1) {
265 return ComparisonChain.start()
266 .compare(arg0.getOrder(), arg1.getOrder(), Ordering.natural().nullsLast())
267 .compare(arg0.getName().getValue(), arg1.getName().getValue(), Ordering.natural().nullsLast())
273 private void syncDirection(FlowMap flowMap, NodeId nodeId, IndexedTenant contractTenant, CgPair cgPair, Rule rule,
274 Direction direction, int priority) {
276 * Create the ordered action list. The implicit action is "allow", and
277 * is therefore always in the list
279 * TODO: revisit implicit vs. default for "allow" TODO: look into
280 * incorporating operational policy for actions
283 // TODO: can pass Comparator ActionRefComparator to List constructor, rather than
284 // referencing in sort
285 List<ActionBuilder> abl = new ArrayList<ActionBuilder>();
286 if (rule.getActionRef() != null) {
288 * Pre-sort by references using order, then name
290 List<ActionRef> arl = new ArrayList<ActionRef>(rule.getActionRef());
291 Collections.sort(arl, ActionRefComparator.INSTANCE);
293 for (ActionRef ar : arl) {
294 ActionInstance ai = contractTenant.getAction(ar.getName());
296 // XXX TODO fail the match and raise an exception
297 LOG.warn("Action instance {} not found", ar.getName().getValue());
300 Action act = SubjectFeatures.getAction(ai.getActionDefinitionId());
302 // XXX TODO fail the match and raise an exception
303 LOG.warn("Action definition {} not found", ai.getActionDefinitionId().getValue());
307 Map<String, Object> params = new HashMap<>();
308 if (ai.getParameterValue() != null) {
309 for (ParameterValue v : ai.getParameterValue()) {
310 if (v.getName() == null)
312 if (v.getIntValue() != null) {
313 params.put(v.getName().getValue(), v.getIntValue());
314 } else if (v.getStringValue() != null) {
315 params.put(v.getName().getValue(), v.getStringValue());
320 * Convert the GBP Action to one or more OpenFlow Actions
322 abl = act.updateAction(abl, params, ar.getOrder());
325 Action act = SubjectFeatures.getAction(AllowAction.DEFINITION.getId());
326 abl = act.updateAction(abl, new HashMap<String, Object>(), 0);
329 Map<String, ParameterValue> paramsFromClassifier = new HashMap<>();
330 Set<ClassifierDefinitionId> classifiers = new HashSet<>();
331 for (ClassifierRef cr : rule.getClassifierRef()) {
332 if (cr.getDirection() != null && !cr.getDirection().equals(Direction.Bidirectional)
333 && !cr.getDirection().equals(direction)) {
337 // XXX - TODO - implement connection tracking (requires openflow
338 // extension and data plane support - in 2.4. Will need to handle
339 // case where we are working with mix of nodes.
341 ClassifierInstance ci = contractTenant.getClassifier(cr.getName());
343 // XXX TODO fail the match and raise an exception
344 LOG.warn("Classifier instance {} not found", cr.getName().getValue());
347 Classifier cfier = SubjectFeatures.getClassifier(ci.getClassifierDefinitionId());
349 // XXX TODO fail the match and raise an exception
350 LOG.warn("Classifier definition {} not found", ci.getClassifierDefinitionId().getValue());
353 classifiers.add(new ClassifierDefinitionId(ci.getClassifierDefinitionId()));
354 for (ParameterValue v : ci.getParameterValue()) {
356 if (v.getIntValue() != null) {
357 paramsFromClassifier.put(v.getName().getValue(), v);
358 } else if (v.getStringValue() != null) {
359 paramsFromClassifier.put(v.getName().getValue(), v);
360 } else if (v.getRangeValue() != null) {
361 paramsFromClassifier.put(v.getName().getValue(), v);
365 List<Map<String, ParameterValue>> derivedParamsByName = ParamDerivator.ETHER_TYPE_DERIVATOR.deriveParameter(paramsFromClassifier);
367 for (Map<String, ParameterValue> params : derivedParamsByName) {
368 for (ClassifierDefinitionId clDefId : classifiers) {
369 Classifier classifier = SubjectFeatures.getClassifier(clDefId);
370 StringBuilder idb = new StringBuilder();
371 // XXX - TODO - implement connection tracking (requires openflow
372 // extension and data plane support - in 2.4. Will need to handle
373 // case where we are working with mix of nodes.
375 MatchBuilder baseMatch = new MatchBuilder();
376 if (direction.equals(Direction.In)) {
377 idb.append(cgPair.sepg)
379 .append(cgPair.scgId)
383 .append(cgPair.dcgId)
386 addNxRegMatch(baseMatch, RegMatch.of(NxmNxReg0.class, Long.valueOf(cgPair.sepg)),
387 RegMatch.of(NxmNxReg1.class, Long.valueOf(cgPair.scgId)),
388 RegMatch.of(NxmNxReg2.class, Long.valueOf(cgPair.depg)),
389 RegMatch.of(NxmNxReg3.class, Long.valueOf(cgPair.dcgId)));
391 idb.append(cgPair.depg)
393 .append(cgPair.dcgId)
397 .append(cgPair.scgId)
400 addNxRegMatch(baseMatch, RegMatch.of(NxmNxReg0.class, Long.valueOf(cgPair.depg)),
401 RegMatch.of(NxmNxReg1.class, Long.valueOf(cgPair.dcgId)),
402 RegMatch.of(NxmNxReg2.class, Long.valueOf(cgPair.sepg)),
403 RegMatch.of(NxmNxReg3.class, Long.valueOf(cgPair.scgId)));
406 List<MatchBuilder> matches = new ArrayList<>();
407 matches.add(baseMatch);
409 ClassificationResult result = classifier.updateMatch(matches, params);
410 if (!result.isSuccessfull()) {
411 // TODO consider different handling.
412 throw new IllegalArgumentException(result.getErrorMessage());
414 String baseId = idb.toString();
415 FlowBuilder flow = base().setPriority(Integer.valueOf(priority));
416 for (MatchBuilder match : result.getMatchBuilders()) {
417 Match m = match.build();
418 FlowId flowId = new FlowId(baseId + "|" + m.toString());
421 .setPriority(Integer.valueOf(priority))
422 .setInstructions(instructions(applyActionIns(abl)));
423 flowMap.writeFlow(nodeId, TABLE_ID, flow.build());
430 private static class CgPair {
432 private final int sepg;
433 private final int depg;
434 private final int scgId;
435 private final int dcgId;
437 public CgPair(int sepg, int depg, int scgId, int dcgId) {
446 public int hashCode() {
447 final int prime = 31;
449 result = prime * result + dcgId;
450 result = prime * result + depg;
451 result = prime * result + scgId;
452 result = prime * result + sepg;
457 public boolean equals(Object obj) {
462 if (getClass() != obj.getClass())
464 CgPair other = (CgPair) obj;
465 if (dcgId != other.dcgId)
467 if (depg != other.depg)
469 if (scgId != other.scgId)
471 if (sepg != other.sepg)