Merge "Redefining DHCP_TABLE as 19"
[netvirt.git] / vpnservice / aclservice / impl / src / main / java / org / opendaylight / netvirt / aclservice / utils / AclServiceUtils.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
9 package org.opendaylight.netvirt.aclservice.utils;
10
11 import com.google.common.base.Optional;
12 import java.math.BigInteger;
13 import java.util.ArrayList;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.concurrent.ExecutionException;
17 import java.util.concurrent.Future;
18 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
19 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
22 import org.opendaylight.genius.mdsalutil.MDSALUtil;
23 import org.opendaylight.genius.mdsalutil.MatchFieldType;
24 import org.opendaylight.genius.mdsalutil.MatchInfo;
25 import org.opendaylight.genius.mdsalutil.MatchInfoBase;
26 import org.opendaylight.genius.mdsalutil.NwConstants;
27 import org.opendaylight.genius.mdsalutil.packet.IPProtocols;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.Ipv4Acl;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.AclKey;
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.interfaces.rev140508.Interfaces;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInputBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceOutput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeBase;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.InterfaceAcl;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
55 import org.opendaylight.yangtools.yang.binding.DataObject;
56 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
57 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
58 import org.opendaylight.yangtools.yang.common.RpcResult;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 public class AclServiceUtils {
63
64     private static final Logger LOG = LoggerFactory.getLogger(AclServiceUtils.class);
65
66     private AclServiceUtils() { }
67
68     /**
69      * Retrieves the Interface from the datastore.
70      * @param broker the data broker
71      * @param interfaceName the interface name
72      * @return the interface.
73      */
74     public static Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
75         .Interface> getInterface(DataBroker broker, String interfaceName) {
76         return read(broker, LogicalDatastoreType.CONFIGURATION, getInterfaceIdentifier(interfaceName));
77     }
78
79     /**
80      * Builds the interface identifier.
81      * @param interfaceName the interface name.
82      * @return the interface identifier.
83      */
84     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
85         .interfaces.Interface> getInterfaceIdentifier(String interfaceName) {
86         return InstanceIdentifier.builder(Interfaces.class)
87                 .child(
88                     org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
89                     .Interface.class, new InterfaceKey(interfaceName)).build();
90     }
91
92     /**
93      * Retrieves the object from the datastore.
94      * @param broker the data broker.
95      * @param datastoreType the data store type.
96      * @param path the wild card path.
97      * @return the required object.
98      */
99     public static <T extends DataObject> Optional<T> read(
100             DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
101
102         Optional<T> result = Optional.absent();
103         ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
104         try {
105             result = tx.read(datastoreType, path).checkedGet();
106         } catch (ReadFailedException e) {
107             LOG.warn("Failed to read InstanceIdentifier {} from {}", path, datastoreType, e);
108         } finally {
109             tx.close();
110         }
111         return result;
112     }
113
114     /**
115      * Retrieves the acl matching the key from the data store.
116      *
117      * @param broker the data broker
118      * @param aclKey the acl key
119      * @return the acl
120      */
121     public static Acl getAcl(DataBroker broker, String aclKey) {
122         Optional<Acl> optAcl = read(broker,
123             LogicalDatastoreType.CONFIGURATION, getAclInstanceIdentifier(aclKey));
124         if (optAcl.isPresent()) {
125             return optAcl.get();
126         }
127         return null;
128     }
129
130     /** Creates the Acl instance identifier.
131      *
132      * @param aclKey the acl key
133      * @return the instance identifier
134      */
135     public static InstanceIdentifier<Acl> getAclInstanceIdentifier(String aclKey) {
136         return InstanceIdentifier
137                 .builder(AccessLists.class)
138                 .child(Acl.class,
139                         new AclKey(aclKey,Ipv4Acl.class))
140                 .build();
141     }
142
143     /**
144      * Get the data path number for the interface.
145      * @param interfaceManagerRpcService interfaceManagerRpcService instance.
146      * @param ifName the interface name.
147      * @return the dpn.
148      */
149     public static BigInteger getDpnForInterface(OdlInterfaceRpcService interfaceManagerRpcService, String ifName) {
150         BigInteger nodeId = BigInteger.ZERO;
151         try {
152             GetDpidFromInterfaceInput dpIdInput =
153                     new GetDpidFromInterfaceInputBuilder().setIntfName(ifName).build();
154             Future<RpcResult<GetDpidFromInterfaceOutput>> dpIdOutput =
155                     interfaceManagerRpcService.getDpidFromInterface(dpIdInput);
156             RpcResult<GetDpidFromInterfaceOutput> dpIdResult = dpIdOutput.get();
157             if (dpIdResult.isSuccessful()) {
158                 nodeId = dpIdResult.getResult().getDpid();
159             } else {
160                 LOG.error("Could not retrieve DPN Id for interface {}", ifName);
161             }
162         } catch (NullPointerException | InterruptedException | ExecutionException e) {
163             LOG.error("Exception when getting dpn for interface {}", ifName,  e);
164         }
165         return nodeId;
166     }
167
168     /**
169      * Retrieves the interface state.
170      * @param dataBroker the data broker.
171      * @param interfaceName the interface name.
172      * @return the interface state.
173      */
174     public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state
175         .Interface getInterfaceStateFromOperDS(DataBroker dataBroker, String interfaceName) {
176         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
177             .interfaces.state.Interface> ifStateId = buildStateInterfaceId(interfaceName);
178         Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
179             .interfaces.state.Interface> ifStateOptional = MDSALUtil.read(LogicalDatastoreType
180                 .OPERATIONAL, ifStateId, dataBroker);
181         if (!ifStateOptional.isPresent()) {
182             return null;
183         }
184
185         return ifStateOptional.get();
186     }
187
188     /**
189      * Build the interface state.
190      * @param interfaceName the interface name.
191      * @return the interface state.
192      */
193     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
194         .interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
195         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
196             .interfaces.state.Interface> idBuilder = InstanceIdentifier.builder(InterfacesState.class)
197             .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
198             .state.Interface.class, new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces
199             .rev140508.interfaces.state.InterfaceKey(interfaceName));
200         return idBuilder.build();
201     }
202
203     /**
204      * Checks whether port security is enabled for the port.
205      * @param port the port.
206      * @return the port security is enabled/not.
207      */
208     public static boolean isPortSecurityEnabled(Interface port) {
209         if (port == null) {
210             LOG.error("Port is Null");
211             return false;
212         }
213         InterfaceAcl aclInPort = port.getAugmentation(InterfaceAcl.class);
214         if (aclInPort == null) {
215             LOG.error("getSecurityGroupInPortList: no security group associated to Interface port: {}", port.getName());
216             return false;
217         }
218         return aclInPort.isPortSecurityEnabled();
219     }
220
221     /**
222      * Checks whether port security is enabled for the port.
223      * @param port the port.
224      * @return the list of security groups.
225      */
226     public static List<Uuid> getInterfaceAcls(Interface port) {
227         if (port == null) {
228             LOG.error("Port is Null");
229             return null;
230         }
231         InterfaceAcl aclInPort = port.getAugmentation(InterfaceAcl.class);
232         if (aclInPort == null) {
233             LOG.error("getSecurityGroupInPortList: no security group associated}",
234                 port.getName());
235             return null;
236         }
237         return aclInPort.getSecurityGroups();
238     }
239
240     /**
241      * Retrieves the security rule attribute augmentation from the access list.
242      * @param ace the access list entry
243      * @return the security rule attributes
244      */
245     public static SecurityRuleAttr  getAccesssListAttributes(Ace ace) {
246         if (ace == null) {
247             LOG.error("Ace is Null");
248             return null;
249         }
250         SecurityRuleAttr aceAttributes = ace.getAugmentation(SecurityRuleAttr.class);
251         if (aceAttributes == null) {
252             LOG.error("Ace is null");
253             return null;
254         }
255         return aceAttributes;
256     }
257
258     /**
259      * Returns the DHCP match.
260      * @param srcPort the source port.
261      * @param dscPort the destination port.
262      * @return list of matches.
263      */
264     public static List<MatchInfoBase> programDhcpMatches(int srcPort, int dscPort) {
265         List<MatchInfoBase> matches = new ArrayList<>();
266         matches.add(new MatchInfo(MatchFieldType.eth_type,
267                 new long[] { NwConstants.ETHTYPE_IPV4 }));
268         matches.add(new MatchInfo(MatchFieldType.ip_proto,
269                 new long[] { IPProtocols.UDP.intValue() }));
270         matches.add(new MatchInfo(MatchFieldType.udp_dst,
271                 new long[] { srcPort }));
272         matches.add(new MatchInfo(MatchFieldType.udp_src,
273                 new long[] { dscPort}));
274         return matches;
275     }
276
277     /**
278      * Builds the service id.
279      *
280      * @param interfaceName the interface name
281      * @param serviceIndex the service index
282      * @param serviceMode the service mode
283      * @return the instance identifier
284      */
285     public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex,
286             Class<? extends ServiceModeBase> serviceMode) {
287         return InstanceIdentifier.builder(ServiceBindings.class)
288                 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, serviceMode))
289                 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
290     }
291
292     /**
293      * Gets the bound services.
294      *
295      * @param serviceName the service name
296      * @param servicePriority the service priority
297      * @param flowPriority the flow priority
298      * @param cookie the cookie
299      * @param instructions the instructions
300      * @return the bound services
301      */
302     public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
303             BigInteger cookie, List<Instruction> instructions) {
304         StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
305                 .setInstruction(instructions);
306         return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
307                 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
308                 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
309     }
310
311     public static List<Uuid> getUpdatedAclList(Interface updatedPort, Interface currentPort) {
312         if (updatedPort == null) {
313             return null;
314         }
315         List<Uuid> updatedAclList = new ArrayList<>(AclServiceUtils.getInterfaceAcls(updatedPort));
316         if (currentPort == null) {
317             return updatedAclList;
318         }
319         List<Uuid> currentAclList = new ArrayList<>(AclServiceUtils.getInterfaceAcls(currentPort));
320         for (Iterator<Uuid> iterator = updatedAclList.iterator(); iterator.hasNext();) {
321             Uuid updatedAclUuid = iterator.next();
322             for (Uuid currentAclUuid :currentAclList) {
323                 if (updatedAclUuid.getValue().equals(currentAclUuid.getValue())) {
324                     iterator.remove();
325                 }
326             }
327         }
328         return updatedAclList;
329     }
330
331 }