Merge "Revert "Revert "Added feature dependency on odl-ovsdb-southbound-impl"""
[groupbasedpolicy.git] / renderers / ofoverlay / src / main / java / org / opendaylight / groupbasedpolicy / renderer / ofoverlay / flow / PolicyEnforcer.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow;
10
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;
15
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;
22 import java.util.Map;
23 import java.util.Set;
24
25 import javax.annotation.concurrent.Immutable;
26
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;
72
73 import com.google.common.collect.ComparisonChain;
74 import com.google.common.collect.Ordering;
75
76 /**
77  * Manage the table that enforces policy on the traffic. Traffic is denied
78  * unless specifically allowed by policy
79  */
80 public class PolicyEnforcer extends FlowTable {
81
82     protected static final Logger LOG = LoggerFactory.getLogger(PolicyEnforcer.class);
83
84     public static final short TABLE_ID = 3;
85
86     public PolicyEnforcer(OfContext ctx) {
87         super(ctx);
88     }
89
90     @Override
91     public short getTableId() {
92         return TABLE_ID;
93     }
94
95     @Override
96     public void sync(NodeId nodeId, PolicyInfo policyInfo, FlowMap flowMap) throws Exception {
97
98         flowMap.writeFlow(nodeId, TABLE_ID, dropFlow(Integer.valueOf(1), null));
99
100         NodeConnectorId tunPort = ctx.getSwitchManager().getTunnelPort(nodeId);
101         if (tunPort != null) {
102             flowMap.writeFlow(nodeId, TABLE_ID, allowFromTunnel(tunPort));
103         }
104
105         HashSet<CgPair> visitedPairs = new HashSet<>();
106
107         // Used for ARP flows
108         Set<Integer> fdIds = new HashSet<>();
109
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)) {
115                         // mEPG ordinals
116                         EndpointFwdCtxOrdinals srcEpFwdCxtOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx,
117                                 policyInfo, srcEp);
118                         EndpointFwdCtxOrdinals dstEpFwdCxtOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx,
119                                 policyInfo, dstEp);
120                         int dcgId = dstEpFwdCxtOrds.getCgId();
121                         int depgId = dstEpFwdCxtOrds.getEpgId();
122                         int scgId = srcEpFwdCxtOrds.getCgId();
123                         int sepgId = srcEpFwdCxtOrds.getEpgId();
124
125                         fdIds.add(srcEpFwdCxtOrds.getFdId());
126
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);
131
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))
136                             continue;
137                         visitedPairs.add(p);
138                         syncPolicy(flowMap, nodeId, rgs, p);
139
140                         // Reverse
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))
145                             continue;
146                         visitedPairs.add(p);
147                         syncPolicy(flowMap, nodeId, rgs, p);
148                     }
149                 }
150             }
151         }
152
153         // Allow same EPG
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)) {
158
159                 IndexedTenant tenant = ctx.getPolicyResolver().getTenant(srcEpgKey.getTenantId());
160                 EndpointGroup group = tenant.getEndpointGroup(srcEpgKey.getEgId());
161                 IntraGroupPolicy igp = group.getIntraGroupPolicy();
162
163                 if (igp == null || igp.equals(IntraGroupPolicy.Allow)) {
164                     for (Endpoint dstEp : ctx.getEndpointManager().getEndpointsForGroup(srcEpgKey)) {
165                         // mEPG ordinals
166                         // if(visitedEps.contains(dstEp)) {
167                         // continue;
168                         // }
169                         // visitedEps.add(dstEp);
170                         EndpointFwdCtxOrdinals srcEpFwdCxtOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx,
171                                 policyInfo, srcEp);
172                         EndpointFwdCtxOrdinals dstEpFwdCxtOrds = OrdinalFactory.getEndpointFwdCtxOrdinals(ctx,
173                                 policyInfo, dstEp);
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));
178                     }
179                 }
180             }
181         }
182
183         // Write ARP flows per flood domain.
184         for (Integer fdId : fdIds) {
185             flowMap.writeFlow(nodeId, TABLE_ID, createArpFlow(fdId));
186         }
187     }
188
189     private Flow createArpFlow(Integer fdId) {
190
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")
195             .append("|")
196             .append(etherType)
197             .append("|")
198             .append(fdId)
199             .toString());
200
201         MatchBuilder mb = new MatchBuilder().setEthernetMatch(FlowUtils.ethernetMatch(null, null, etherType));
202
203         addNxRegMatch(mb, RegMatch.of(NxmNxReg5.class, Long.valueOf(fdId)));
204
205         Flow flow = base().setPriority(priority)
206             .setId(flowid)
207             .setMatch(mb.build())
208             .setInstructions(instructions(applyActionIns(nxOutputRegAction(NxmNxReg7.class))))
209             .build();
210         return flow;
211     }
212
213     private Flow allowSameEpg(int sepgId, int depgId) {
214
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())
221             .setPriority(65000)
222             .setInstructions(instructions(applyActionIns(nxOutputRegAction(NxmNxReg7.class))));
223         return flow.build();
224     }
225
226     private Flow allowFromTunnel(NodeConnectorId tunPort) {
227
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())
233             .setPriority(65000)
234             .setInstructions(instructions(applyActionIns(nxOutputRegAction(NxmNxReg7.class))));
235         return flow.build();
236
237     }
238
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);
247
248                 priority -= 1;
249             }
250         }
251     }
252
253     /**
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.
258      */
259     private static class ActionRefComparator implements Comparator<ActionRef> {
260
261         public static final ActionRefComparator INSTANCE = new ActionRefComparator();
262
263         @Override
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())
268                 .result();
269         }
270
271     }
272
273     private void syncDirection(FlowMap flowMap, NodeId nodeId, IndexedTenant contractTenant, CgPair cgPair, Rule rule,
274             Direction direction, int priority) {
275         /*
276          * Create the ordered action list. The implicit action is "allow", and
277          * is therefore always in the list
278          *
279          * TODO: revisit implicit vs. default for "allow" TODO: look into
280          * incorporating operational policy for actions
281          */
282
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) {
287             /*
288              * Pre-sort by references using order, then name
289              */
290             List<ActionRef> arl = new ArrayList<ActionRef>(rule.getActionRef());
291             Collections.sort(arl, ActionRefComparator.INSTANCE);
292
293             for (ActionRef ar : arl) {
294                 ActionInstance ai = contractTenant.getAction(ar.getName());
295                 if (ai == null) {
296                     // XXX TODO fail the match and raise an exception
297                     LOG.warn("Action instance {} not found", ar.getName().getValue());
298                     return;
299                 }
300                 Action act = SubjectFeatures.getAction(ai.getActionDefinitionId());
301                 if (act == null) {
302                     // XXX TODO fail the match and raise an exception
303                     LOG.warn("Action definition {} not found", ai.getActionDefinitionId().getValue());
304                     return;
305                 }
306
307                 Map<String, Object> params = new HashMap<>();
308                 if (ai.getParameterValue() != null) {
309                     for (ParameterValue v : ai.getParameterValue()) {
310                         if (v.getName() == null)
311                             continue;
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());
316                         }
317                     }
318                 }
319                 /*
320                  * Convert the GBP Action to one or more OpenFlow Actions
321                  */
322                 abl = act.updateAction(abl, params, ar.getOrder());
323             }
324         } else {
325             Action act = SubjectFeatures.getAction(AllowAction.DEFINITION.getId());
326             abl = act.updateAction(abl, new HashMap<String, Object>(), 0);
327         }
328
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)) {
334                 continue;
335             }
336
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.
340
341             ClassifierInstance ci = contractTenant.getClassifier(cr.getName());
342             if (ci == null) {
343                 // XXX TODO fail the match and raise an exception
344                 LOG.warn("Classifier instance {} not found", cr.getName().getValue());
345                 return;
346             }
347             Classifier cfier = SubjectFeatures.getClassifier(ci.getClassifierDefinitionId());
348             if (cfier == null) {
349                 // XXX TODO fail the match and raise an exception
350                 LOG.warn("Classifier definition {} not found", ci.getClassifierDefinitionId().getValue());
351                 return;
352             }
353             classifiers.add(new ClassifierDefinitionId(ci.getClassifierDefinitionId()));
354             for (ParameterValue v : ci.getParameterValue()) {
355
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);
362                 }
363             }
364         }
365         List<Map<String, ParameterValue>> derivedParamsByName = ParamDerivator.ETHER_TYPE_DERIVATOR.deriveParameter(paramsFromClassifier);
366
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.
374
375                 MatchBuilder baseMatch = new MatchBuilder();
376                 if (direction.equals(Direction.In)) {
377                     idb.append(cgPair.sepg)
378                         .append("|")
379                         .append(cgPair.scgId)
380                         .append("|")
381                         .append(cgPair.depg)
382                         .append("|")
383                         .append(cgPair.dcgId)
384                         .append("|")
385                         .append(priority);
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)));
390                 } else {
391                     idb.append(cgPair.depg)
392                         .append("|")
393                         .append(cgPair.dcgId)
394                         .append("|")
395                         .append(cgPair.sepg)
396                         .append("|")
397                         .append(cgPair.scgId)
398                         .append("|")
399                         .append(priority);
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)));
404                 }
405
406                 List<MatchBuilder> matches = new ArrayList<>();
407                 matches.add(baseMatch);
408
409                 ClassificationResult result = classifier.updateMatch(matches, params);
410                 if (!result.isSuccessfull()) {
411                     // TODO consider different handling.
412                     throw new IllegalArgumentException(result.getErrorMessage());
413                 }
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());
419                     flow.setMatch(m)
420                         .setId(flowId)
421                         .setPriority(Integer.valueOf(priority))
422                         .setInstructions(instructions(applyActionIns(abl)));
423                     flowMap.writeFlow(nodeId, TABLE_ID, flow.build());
424                 }
425             }
426         }
427     }
428
429     @Immutable
430     private static class CgPair {
431
432         private final int sepg;
433         private final int depg;
434         private final int scgId;
435         private final int dcgId;
436
437         public CgPair(int sepg, int depg, int scgId, int dcgId) {
438             super();
439             this.sepg = sepg;
440             this.depg = depg;
441             this.scgId = scgId;
442             this.dcgId = dcgId;
443         }
444
445         @Override
446         public int hashCode() {
447             final int prime = 31;
448             int result = 1;
449             result = prime * result + dcgId;
450             result = prime * result + depg;
451             result = prime * result + scgId;
452             result = prime * result + sepg;
453             return result;
454         }
455
456         @Override
457         public boolean equals(Object obj) {
458             if (this == obj)
459                 return true;
460             if (obj == null)
461                 return false;
462             if (getClass() != obj.getClass())
463                 return false;
464             CgPair other = (CgPair) obj;
465             if (dcgId != other.dcgId)
466                 return false;
467             if (depg != other.depg)
468                 return false;
469             if (scgId != other.scgId)
470                 return false;
471             if (sepg != other.sepg)
472                 return false;
473             return true;
474         }
475     }
476 }