InstructionInfo redesign
[netvirt.git] / vpnservice / aclservice / impl / src / main / java / org / opendaylight / netvirt / aclservice / AbstractAclServiceImpl.java
1 /*
2  * Copyright (c) 2016 Red Hat, 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 package org.opendaylight.netvirt.aclservice;
9
10 import java.math.BigInteger;
11 import java.util.ArrayList;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.Map.Entry;
15 import java.util.Set;
16
17 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
18 import org.opendaylight.genius.mdsalutil.ActionInfo;
19 import org.opendaylight.genius.mdsalutil.FlowEntity;
20 import org.opendaylight.genius.mdsalutil.InstructionInfo;
21 import org.opendaylight.genius.mdsalutil.MDSALUtil;
22 import org.opendaylight.genius.mdsalutil.MatchInfoBase;
23 import org.opendaylight.genius.mdsalutil.NwConstants;
24 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
25 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
26 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
27 import org.opendaylight.netvirt.aclservice.api.AclServiceListener;
28 import org.opendaylight.netvirt.aclservice.api.AclServiceManager.Action;
29 import org.opendaylight.netvirt.aclservice.api.utils.AclInterface;
30 import org.opendaylight.netvirt.aclservice.utils.AclDataUtil;
31 import org.opendaylight.netvirt.aclservice.utils.AclServiceUtils;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeBase;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeEgress;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public abstract class AbstractAclServiceImpl implements AclServiceListener {
41
42     private static final Logger LOG = LoggerFactory.getLogger(AbstractAclServiceImpl.class);
43
44     protected final IMdsalApiManager mdsalManager;
45     protected final DataBroker dataBroker;
46     protected final Class<? extends ServiceModeBase> serviceMode;
47     protected final AclDataUtil aclDataUtil;
48     protected final AclServiceUtils aclServiceUtils;
49
50     /**
51      * Initialize the member variables.
52      *
53      * @param serviceMode
54      *            the service mode
55      * @param dataBroker
56      *            the data broker instance.
57      * @param mdsalManager
58      *            the mdsal manager instance.
59      * @param aclDataUtil
60      *            the acl data util.
61      * @param aclServiceUtils
62      *            the acl service util.
63      */
64     public AbstractAclServiceImpl(Class<? extends ServiceModeBase> serviceMode, DataBroker dataBroker,
65             IMdsalApiManager mdsalManager, AclDataUtil aclDataUtil, AclServiceUtils aclServiceUtils) {
66         this.dataBroker = dataBroker;
67         this.mdsalManager = mdsalManager;
68         this.serviceMode = serviceMode;
69         this.aclDataUtil = aclDataUtil;
70         this.aclServiceUtils = aclServiceUtils;
71     }
72
73     @Override
74     public boolean applyAcl(AclInterface port) {
75         if (port == null) {
76             LOG.error("port cannot be null");
77             return false;
78         }
79         if (port.getSecurityGroups() == null) {
80             LOG.error("port security groups cannot be null");
81             return false;
82         }
83         BigInteger dpId = port.getDpId();
84         if (dpId == null || port.getLPortTag() == null) {
85             LOG.error("Unable to find DP Id from ACL interface with id {}", port.getInterfaceId());
86             return false;
87         }
88         programAclWithAllowedAddress(dpId, port.getAllowedAddressPairs(), port.getLPortTag(), port.getSecurityGroups(),
89                 Action.ADD, NwConstants.ADD_FLOW, port.getInterfaceId());
90
91         bindService(port.getInterfaceId());
92         return true;
93     }
94
95     @Override
96     public boolean updateAcl(AclInterface portBefore, AclInterface portAfter) {
97         boolean result = true;
98         boolean isPortSecurityEnable = portAfter.getPortSecurityEnabled();
99         boolean isPortSecurityEnableBefore = portBefore.getPortSecurityEnabled();
100         // if port security is changed, apply/remove Acls
101         if (isPortSecurityEnableBefore != isPortSecurityEnable) {
102             if (isPortSecurityEnable) {
103                 result = applyAcl(portAfter);
104             } else {
105                 result = removeAcl(portAfter);
106             }
107         } else if (isPortSecurityEnable) {
108             // Acls has been updated, find added/removed Acls and act accordingly.
109             processInterfaceUpdate(portBefore, portAfter);
110         }
111
112         return result;
113     }
114
115     private void processInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
116         BigInteger dpId = portAfter.getDpId();
117         List<AllowedAddressPairs> addedAllowedAddressPairs =
118                 AclServiceUtils.getUpdatedAllowedAddressPairs(portAfter.getAllowedAddressPairs(),
119                         portBefore.getAllowedAddressPairs());
120         List<AllowedAddressPairs> deletedAllowedAddressPairs =
121                 AclServiceUtils.getUpdatedAllowedAddressPairs(portBefore.getAllowedAddressPairs(),
122                         portAfter.getAllowedAddressPairs());
123         if (addedAllowedAddressPairs != null && !addedAllowedAddressPairs.isEmpty()) {
124             programAclWithAllowedAddress(dpId, addedAllowedAddressPairs, portAfter.getLPortTag(),
125                     portAfter.getSecurityGroups(), Action.UPDATE, NwConstants.ADD_FLOW, portAfter.getInterfaceId());
126         }
127         if (deletedAllowedAddressPairs != null && !deletedAllowedAddressPairs.isEmpty()) {
128             programAclWithAllowedAddress(dpId, deletedAllowedAddressPairs, portAfter.getLPortTag(),
129                     portAfter.getSecurityGroups(), Action.UPDATE, NwConstants.DEL_FLOW, portAfter.getInterfaceId());
130         }
131
132         List<Uuid> addedAcls = AclServiceUtils.getUpdatedAclList(portAfter.getSecurityGroups(),
133                 portBefore.getSecurityGroups());
134         List<Uuid> deletedAcls = AclServiceUtils.getUpdatedAclList(portBefore.getSecurityGroups(),
135                 portAfter.getSecurityGroups());
136         if (deletedAcls != null && !deletedAcls.isEmpty()) {
137             updateCustomRules(dpId, portAfter.getLPortTag(), deletedAcls, NwConstants.DEL_FLOW,
138                     portAfter.getInterfaceId(), portAfter.getAllowedAddressPairs());
139         }
140         if (addedAcls != null && !addedAcls.isEmpty()) {
141             updateCustomRules(dpId, portAfter.getLPortTag(), addedAcls, NwConstants.ADD_FLOW,
142                     portAfter.getInterfaceId(), portAfter.getAllowedAddressPairs());
143         }
144     }
145
146     private void updateCustomRules(BigInteger dpId, int lportTag, List<Uuid> aclUuidList, int action,
147                                    String portId, List<AllowedAddressPairs> syncAllowedAddresses) {
148         programAclRules(aclUuidList, dpId, lportTag, action, portId);
149         syncRemoteAclRules(aclUuidList, action, portId, syncAllowedAddresses);
150     }
151
152     private void syncRemoteAclRules(List<Uuid> aclUuidList, int action, String currentPortId,
153                                     List<AllowedAddressPairs> syncAllowedAddresses) {
154         if (aclUuidList == null) {
155             LOG.warn("security groups are null");
156             return;
157         }
158         for (Uuid remoteAclId : aclUuidList) {
159             Map<String, Set<AclInterface>> mapAclWithPortSet = aclDataUtil.getRemoteAclInterfaces(remoteAclId);
160             if (mapAclWithPortSet == null) {
161                 continue;
162             }
163             for (Entry<String, Set<AclInterface>> entry : mapAclWithPortSet.entrySet()) {
164                 String aclName = entry.getKey();
165                 for (AclInterface port : entry.getValue()) {
166                     if (currentPortId.equals(port.getInterfaceId())) {
167                         continue;
168                     }
169                     List<Ace> remoteAceList = AclServiceUtils.getAceWithRemoteAclId(dataBroker, port, remoteAclId);
170                     for (Ace ace : remoteAceList) {
171                         programAceRule(port.getDpId(), port.getLPortTag(), action, aclName, ace, port.getInterfaceId(),
172                                 syncAllowedAddresses);
173                     }
174                 }
175             }
176         }
177     }
178
179     private void programAclWithAllowedAddress(BigInteger dpId, List<AllowedAddressPairs> allowedAddresses,
180                                               int lportTag, List<Uuid> aclUuidList, Action action, int addOrRemove,
181                                               String portId) {
182         programGeneralFixedRules(dpId, "", allowedAddresses, lportTag, action, addOrRemove);
183         programSpecificFixedRules(dpId, "", allowedAddresses, lportTag, portId, action, addOrRemove);
184         if (action == Action.ADD || action == Action.REMOVE) {
185             programAclRules(aclUuidList, dpId, lportTag, addOrRemove, portId);
186         }
187         syncRemoteAclRules(aclUuidList, addOrRemove, portId, allowedAddresses);
188     }
189
190
191     @Override
192     public boolean removeAcl(AclInterface port) {
193         BigInteger dpId = port.getDpId();
194         if (dpId == null) {
195             LOG.error("Unable to find DP Id from ACL interface with id {}", port.getInterfaceId());
196             return false;
197         }
198         programAclWithAllowedAddress(dpId, port.getAllowedAddressPairs(), port.getLPortTag(), port.getSecurityGroups(),
199                 Action.REMOVE, NwConstants.DEL_FLOW, port.getInterfaceId());
200
201         unbindService(port.getInterfaceId());
202         return true;
203     }
204
205     @Override
206     public boolean applyAce(AclInterface port, String aclName, Ace ace) {
207         if (!port.isPortSecurityEnabled()) {
208             return false;
209         }
210         programAceRule(port.getDpId(), port.getLPortTag(), NwConstants.ADD_FLOW, aclName, ace, port.getInterfaceId(),
211                 null);
212         return true;
213     }
214
215     @Override
216     public boolean removeAce(AclInterface port, String aclName, Ace ace) {
217         if (!port.isPortSecurityEnabled()) {
218             return false;
219         }
220         programAceRule(port.getDpId(), port.getLPortTag(), NwConstants.DEL_FLOW, aclName, ace, port.getInterfaceId(),
221                 null);
222         return true;
223     }
224
225     /**
226      * Bind service.
227      *
228      * @param interfaceName
229      *            the interface name
230      */
231     protected abstract void bindService(String interfaceName);
232
233     /**
234      * Unbind service.
235      *
236      * @param interfaceName
237      *            the interface name
238      */
239     protected abstract void unbindService(String interfaceName);
240
241     /**
242      * Program the default anti-spoofing rules.
243      *
244      * @param dpid the dpid
245      * @param dhcpMacAddress the dhcp mac address.
246      * @param allowedAddresses the allowed addresses
247      * @param lportTag the lport tag
248      * @param action add/modify/remove action
249      * @param addOrRemove addorRemove
250      */
251     protected abstract void programGeneralFixedRules(BigInteger dpid, String dhcpMacAddress,
252             List<AllowedAddressPairs> allowedAddresses, int lportTag, Action action, int addOrRemove);
253
254     /**
255      * Program the default specific rules.
256      *
257      * @param dpid the dpid
258      * @param dhcpMacAddress the dhcp mac address.
259      * @param allowedAddresses the allowed addresses
260      * @param lportTag the lport tag
261      * @param portId the port id
262      * @param action add/modify/remove action
263      * @param addOrRemove addorRemove
264      */
265     protected abstract void programSpecificFixedRules(BigInteger dpid, String dhcpMacAddress,
266             List<AllowedAddressPairs> allowedAddresses, int lportTag, String portId, Action action, int addOrRemove);
267
268     /**
269      * Programs the acl custom rules.
270      *
271      * @param aclUuidList the list of acl uuid to be applied
272      * @param dpId the dpId
273      * @param lportTag the lport tag
274      * @param addOrRemove whether to delete or add flow
275      * @param portId the port id
276      * @return program succeeded
277      */
278     protected abstract boolean programAclRules(List<Uuid> aclUuidList, BigInteger dpId, int lportTag, int addOrRemove,
279                                             String portId);
280
281     /**
282      * Programs the ace custom rule.
283      *
284      * @param dpId the dpId
285      * @param lportTag the lport tag
286      * @param addOrRemove whether to delete or add flow
287      * @param aclName the acl name
288      * @param ace rule to be program
289      * @param portId the port id
290      * @param syncAllowedAddresses the allowed addresses
291      */
292     protected abstract void programAceRule(BigInteger dpId, int lportTag, int addOrRemove, String aclName, Ace ace,
293             String portId, List<AllowedAddressPairs> syncAllowedAddresses);
294
295     /**
296      * Writes/remove the flow to/from the datastore.
297      *
298      * @param dpId
299      *            the dpId
300      * @param tableId
301      *            the tableId
302      * @param flowId
303      *            the flowId
304      * @param priority
305      *            the priority
306      * @param flowName
307      *            the flow name
308      * @param idleTimeOut
309      *            the idle timeout
310      * @param hardTimeOut
311      *            the hard timeout
312      * @param cookie
313      *            the cookie
314      * @param matches
315      *            the list of matches to be writted
316      * @param instructions
317      *            the list of instruction to be written.
318      * @param addOrRemove
319      *            add or remove the entries.
320      */
321     protected void syncFlow(BigInteger dpId, short tableId, String flowId, int priority, String flowName,
322             int idleTimeOut, int hardTimeOut, BigInteger cookie, List<? extends MatchInfoBase> matches,
323             List<InstructionInfo> instructions, int addOrRemove) {
324         if (addOrRemove == NwConstants.DEL_FLOW) {
325             FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, tableId, flowId, priority, flowName, idleTimeOut,
326                     hardTimeOut, cookie, matches, null);
327             LOG.trace("Removing Acl Flow DpnId {}, flowId {}", dpId, flowId);
328             mdsalManager.removeFlow(flowEntity);
329         } else {
330             FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, tableId, flowId, priority, flowName, idleTimeOut,
331                     hardTimeOut, cookie, matches, instructions);
332             LOG.trace("Installing DpnId {}, flowId {}", dpId, flowId);
333             mdsalManager.installFlow(flowEntity);
334         }
335     }
336
337     /**
338      * Gets the dispatcher table resubmit instructions based on ingress/egress
339      * service mode w.r.t switch.
340      *
341      * @param actionsInfos the actions infos
342      * @return the instructions for dispatcher table resubmit
343      */
344     protected List<InstructionInfo> getDispatcherTableResubmitInstructions(List<ActionInfo> actionsInfos) {
345         short dispatcherTableId = NwConstants.LPORT_DISPATCHER_TABLE;
346         if (ServiceModeEgress.class.equals(this.serviceMode)) {
347             dispatcherTableId = NwConstants.EGRESS_LPORT_DISPATCHER_TABLE;
348         }
349
350         List<InstructionInfo> instructions = new ArrayList<>();
351         actionsInfos.add(new ActionNxResubmit(dispatcherTableId));
352         instructions.add(new InstructionApplyActions(actionsInfos));
353         return instructions;
354     }
355
356     protected String getOperAsString(int flowOper) {
357         String oper;
358         switch (flowOper) {
359             case NwConstants.ADD_FLOW:
360                 oper = "Add";
361                 break;
362             case NwConstants.DEL_FLOW:
363                 oper = "Del";
364                 break;
365             case NwConstants.MOD_FLOW:
366                 oper = "Mod";
367                 break;
368             default:
369                 oper = "UNKNOWN";
370         }
371         return oper;
372     }
373
374 }