Revert "Bug 7775: Updated to use DataStoreJobCoordinator for flow programming"
[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         return true;
91     }
92
93     @Override
94     public boolean bindAcl(AclInterface port) {
95         if (port == null || port.getSecurityGroups() == null) {
96             LOG.error("port and port security groups cannot be null");
97             return false;
98         }
99         bindService(port.getInterfaceId());
100         return true;
101     }
102
103     @Override
104     public boolean unbindAcl(AclInterface port) {
105         BigInteger dpId = port.getDpId();
106         if (dpId == null) {
107             LOG.error("Unable to find DP Id from ACL interface with id {}", port.getInterfaceId());
108             return false;
109         }
110         unbindService(port.getInterfaceId());
111         return true;
112     }
113
114     @Override
115     public boolean updateAcl(AclInterface portBefore, AclInterface portAfter) {
116         boolean result = true;
117         boolean isPortSecurityEnable = portAfter.getPortSecurityEnabled();
118         boolean isPortSecurityEnableBefore = portBefore.getPortSecurityEnabled();
119         // if port security is changed, apply/remove Acls
120         if (isPortSecurityEnableBefore != isPortSecurityEnable) {
121             if (isPortSecurityEnable) {
122                 result = applyAcl(portAfter) && bindAcl(portAfter);
123             } else {
124                 result = removeAcl(portAfter) && unbindAcl(portAfter);
125             }
126         } else if (isPortSecurityEnable) {
127             // Acls has been updated, find added/removed Acls and act accordingly.
128             processInterfaceUpdate(portBefore, portAfter);
129         }
130
131         return result;
132     }
133
134     private void processInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
135         BigInteger dpId = portAfter.getDpId();
136         List<AllowedAddressPairs> addedAllowedAddressPairs =
137                 AclServiceUtils.getUpdatedAllowedAddressPairs(portAfter.getAllowedAddressPairs(),
138                         portBefore.getAllowedAddressPairs());
139         List<AllowedAddressPairs> deletedAllowedAddressPairs =
140                 AclServiceUtils.getUpdatedAllowedAddressPairs(portBefore.getAllowedAddressPairs(),
141                         portAfter.getAllowedAddressPairs());
142         if (addedAllowedAddressPairs != null && !addedAllowedAddressPairs.isEmpty()) {
143             programAclWithAllowedAddress(dpId, addedAllowedAddressPairs, portAfter.getLPortTag(),
144                     portAfter.getSecurityGroups(), Action.UPDATE, NwConstants.ADD_FLOW, portAfter.getInterfaceId());
145         }
146         if (deletedAllowedAddressPairs != null && !deletedAllowedAddressPairs.isEmpty()) {
147             programAclWithAllowedAddress(dpId, deletedAllowedAddressPairs, portAfter.getLPortTag(),
148                     portAfter.getSecurityGroups(), Action.UPDATE, NwConstants.DEL_FLOW, portAfter.getInterfaceId());
149         }
150
151         List<Uuid> addedAcls = AclServiceUtils.getUpdatedAclList(portAfter.getSecurityGroups(),
152                 portBefore.getSecurityGroups());
153         List<Uuid> deletedAcls = AclServiceUtils.getUpdatedAclList(portBefore.getSecurityGroups(),
154                 portAfter.getSecurityGroups());
155         if (deletedAcls != null && !deletedAcls.isEmpty()) {
156             updateCustomRules(dpId, portAfter.getLPortTag(), deletedAcls, NwConstants.DEL_FLOW,
157                     portAfter.getInterfaceId(), portAfter.getAllowedAddressPairs());
158         }
159         if (addedAcls != null && !addedAcls.isEmpty()) {
160             updateCustomRules(dpId, portAfter.getLPortTag(), addedAcls, NwConstants.ADD_FLOW,
161                     portAfter.getInterfaceId(), portAfter.getAllowedAddressPairs());
162         }
163     }
164
165     private void updateCustomRules(BigInteger dpId, int lportTag, List<Uuid> aclUuidList, int action,
166                                    String portId, List<AllowedAddressPairs> syncAllowedAddresses) {
167         programAclRules(aclUuidList, dpId, lportTag, action, portId);
168         syncRemoteAclRules(aclUuidList, action, portId, syncAllowedAddresses);
169     }
170
171     private void syncRemoteAclRules(List<Uuid> aclUuidList, int action, String currentPortId,
172                                     List<AllowedAddressPairs> syncAllowedAddresses) {
173         if (aclUuidList == null) {
174             LOG.warn("security groups are null");
175             return;
176         }
177         for (Uuid remoteAclId : aclUuidList) {
178             Map<String, Set<AclInterface>> mapAclWithPortSet = aclDataUtil.getRemoteAclInterfaces(remoteAclId);
179             if (mapAclWithPortSet == null) {
180                 continue;
181             }
182             for (Entry<String, Set<AclInterface>> entry : mapAclWithPortSet.entrySet()) {
183                 String aclName = entry.getKey();
184                 for (AclInterface port : entry.getValue()) {
185                     if (currentPortId.equals(port.getInterfaceId())) {
186                         continue;
187                     }
188                     List<Ace> remoteAceList = AclServiceUtils.getAceWithRemoteAclId(dataBroker, port, remoteAclId);
189                     for (Ace ace : remoteAceList) {
190                         programAceRule(port.getDpId(), port.getLPortTag(), action, aclName, ace, port.getInterfaceId(),
191                                 syncAllowedAddresses);
192                     }
193                 }
194             }
195         }
196     }
197
198     private void programAclWithAllowedAddress(BigInteger dpId, List<AllowedAddressPairs> allowedAddresses,
199                                               int lportTag, List<Uuid> aclUuidList, Action action, int addOrRemove,
200                                               String portId) {
201         programGeneralFixedRules(dpId, "", allowedAddresses, lportTag, action, addOrRemove);
202         programSpecificFixedRules(dpId, "", allowedAddresses, lportTag, portId, action, addOrRemove);
203         if (action == Action.ADD || action == Action.REMOVE) {
204             programAclRules(aclUuidList, dpId, lportTag, addOrRemove, portId);
205         }
206         syncRemoteAclRules(aclUuidList, addOrRemove, portId, allowedAddresses);
207     }
208
209
210     @Override
211     public boolean removeAcl(AclInterface port) {
212         BigInteger dpId = port.getDpId();
213         if (dpId == null) {
214             LOG.error("Unable to find DP Id from ACL interface with id {}", port.getInterfaceId());
215             return false;
216         }
217         programAclWithAllowedAddress(dpId, port.getAllowedAddressPairs(), port.getLPortTag(), port.getSecurityGroups(),
218                 Action.REMOVE, NwConstants.DEL_FLOW, port.getInterfaceId());
219         return true;
220     }
221
222     @Override
223     public boolean applyAce(AclInterface port, String aclName, Ace ace) {
224         if (!port.isPortSecurityEnabled()) {
225             return false;
226         }
227         programAceRule(port.getDpId(), port.getLPortTag(), NwConstants.ADD_FLOW, aclName, ace, port.getInterfaceId(),
228                 null);
229         return true;
230     }
231
232     @Override
233     public boolean removeAce(AclInterface port, String aclName, Ace ace) {
234         if (!port.isPortSecurityEnabled()) {
235             return false;
236         }
237         programAceRule(port.getDpId(), port.getLPortTag(), NwConstants.DEL_FLOW, aclName, ace, port.getInterfaceId(),
238                 null);
239         return true;
240     }
241
242     /**
243      * Bind service.
244      *
245      * @param interfaceName
246      *            the interface name
247      */
248     protected abstract void bindService(String interfaceName);
249
250     /**
251      * Unbind service.
252      *
253      * @param interfaceName
254      *            the interface name
255      */
256     protected abstract void unbindService(String interfaceName);
257
258     /**
259      * Program the default anti-spoofing rules.
260      *
261      * @param dpid the dpid
262      * @param dhcpMacAddress the dhcp mac address.
263      * @param allowedAddresses the allowed addresses
264      * @param lportTag the lport tag
265      * @param action add/modify/remove action
266      * @param addOrRemove addorRemove
267      */
268     protected abstract void programGeneralFixedRules(BigInteger dpid, String dhcpMacAddress,
269             List<AllowedAddressPairs> allowedAddresses, int lportTag, Action action, int addOrRemove);
270
271     /**
272      * Program the default specific rules.
273      *
274      * @param dpid the dpid
275      * @param dhcpMacAddress the dhcp mac address.
276      * @param allowedAddresses the allowed addresses
277      * @param lportTag the lport tag
278      * @param portId the port id
279      * @param action add/modify/remove action
280      * @param addOrRemove addorRemove
281      */
282     protected abstract void programSpecificFixedRules(BigInteger dpid, String dhcpMacAddress,
283             List<AllowedAddressPairs> allowedAddresses, int lportTag, String portId, Action action, int addOrRemove);
284
285     /**
286      * Programs the acl custom rules.
287      *
288      * @param aclUuidList the list of acl uuid to be applied
289      * @param dpId the dpId
290      * @param lportTag the lport tag
291      * @param addOrRemove whether to delete or add flow
292      * @param portId the port id
293      * @return program succeeded
294      */
295     protected abstract boolean programAclRules(List<Uuid> aclUuidList, BigInteger dpId, int lportTag, int addOrRemove,
296                                             String portId);
297
298     /**
299      * Programs the ace custom rule.
300      *
301      * @param dpId the dpId
302      * @param lportTag the lport tag
303      * @param addOrRemove whether to delete or add flow
304      * @param aclName the acl name
305      * @param ace rule to be program
306      * @param portId the port id
307      * @param syncAllowedAddresses the allowed addresses
308      */
309     protected abstract void programAceRule(BigInteger dpId, int lportTag, int addOrRemove, String aclName, Ace ace,
310             String portId, List<AllowedAddressPairs> syncAllowedAddresses);
311
312     /**
313      * Writes/remove the flow to/from the datastore.
314      *
315      * @param dpId
316      *            the dpId
317      * @param tableId
318      *            the tableId
319      * @param flowId
320      *            the flowId
321      * @param priority
322      *            the priority
323      * @param flowName
324      *            the flow name
325      * @param idleTimeOut
326      *            the idle timeout
327      * @param hardTimeOut
328      *            the hard timeout
329      * @param cookie
330      *            the cookie
331      * @param matches
332      *            the list of matches to be writted
333      * @param instructions
334      *            the list of instruction to be written.
335      * @param addOrRemove
336      *            add or remove the entries.
337      */
338     protected void syncFlow(BigInteger dpId, short tableId, String flowId, int priority, String flowName,
339             int idleTimeOut, int hardTimeOut, BigInteger cookie, List<? extends MatchInfoBase> matches,
340             List<InstructionInfo> instructions, int addOrRemove) {
341         if (addOrRemove == NwConstants.DEL_FLOW) {
342             FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, tableId, flowId, priority, flowName, idleTimeOut,
343                     hardTimeOut, cookie, matches, null);
344             LOG.trace("Removing Acl Flow DpnId {}, flowId {}", dpId, flowId);
345             mdsalManager.removeFlow(flowEntity);
346         } else {
347             FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, tableId, flowId, priority, flowName, idleTimeOut,
348                     hardTimeOut, cookie, matches, instructions);
349             LOG.trace("Installing DpnId {}, flowId {}", dpId, flowId);
350             mdsalManager.installFlow(flowEntity);
351         }
352     }
353
354     /**
355      * Gets the dispatcher table resubmit instructions based on ingress/egress
356      * service mode w.r.t switch.
357      *
358      * @param actionsInfos the actions infos
359      * @return the instructions for dispatcher table resubmit
360      */
361     protected List<InstructionInfo> getDispatcherTableResubmitInstructions(List<ActionInfo> actionsInfos) {
362         short dispatcherTableId = NwConstants.LPORT_DISPATCHER_TABLE;
363         if (ServiceModeEgress.class.equals(this.serviceMode)) {
364             dispatcherTableId = NwConstants.EGRESS_LPORT_DISPATCHER_TABLE;
365         }
366
367         List<InstructionInfo> instructions = new ArrayList<>();
368         actionsInfos.add(new ActionNxResubmit(dispatcherTableId));
369         instructions.add(new InstructionApplyActions(actionsInfos));
370         return instructions;
371     }
372
373     protected String getOperAsString(int flowOper) {
374         String oper;
375         switch (flowOper) {
376             case NwConstants.ADD_FLOW:
377                 oper = "Add";
378                 break;
379             case NwConstants.DEL_FLOW:
380                 oper = "Del";
381                 break;
382             case NwConstants.MOD_FLOW:
383                 oper = "Mod";
384                 break;
385             default:
386                 oper = "UNKNOWN";
387         }
388         return oper;
389     }
390
391 }