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