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