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