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