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