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