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