58b448ec7fcfdc18d4b5b62d3dd0f1e12bf6324f
[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.MetaDataUtil;
27 import org.opendaylight.genius.mdsalutil.NwConstants;
28 import org.opendaylight.genius.mdsalutil.packet.IPProtocols;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.Ipv4Acl;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.AclKey;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInputBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceOutput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeBase;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.InterfaceAcl;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.IpPrefixOrAddress;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
61 import org.opendaylight.yangtools.yang.binding.DataObject;
62 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
63 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
64 import org.opendaylight.yangtools.yang.common.RpcResult;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 public class AclServiceUtils {
69
70     private static final Logger LOG = LoggerFactory.getLogger(AclServiceUtils.class);
71
72     private AclServiceUtils() { }
73
74     /**
75      * Retrieves the Interface from the datastore.
76      * @param broker the data broker
77      * @param interfaceName the interface name
78      * @return the interface.
79      */
80     public static Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
81         .Interface> getInterface(DataBroker broker, String interfaceName) {
82         return read(broker, LogicalDatastoreType.CONFIGURATION, getInterfaceIdentifier(interfaceName));
83     }
84
85     /**
86      * Builds the interface identifier.
87      * @param interfaceName the interface name.
88      * @return the interface identifier.
89      */
90     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
91         .interfaces.Interface> getInterfaceIdentifier(String interfaceName) {
92         return InstanceIdentifier.builder(Interfaces.class)
93                 .child(
94                     org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
95                     .Interface.class, new InterfaceKey(interfaceName)).build();
96     }
97
98     /**
99      * Retrieves the object from the datastore.
100      * @param broker the data broker.
101      * @param datastoreType the data store type.
102      * @param path the wild card path.
103      * @return the required object.
104      */
105     public static <T extends DataObject> Optional<T> read(
106             DataBroker broker, LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
107
108         Optional<T> result = Optional.absent();
109         ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
110         try {
111             result = tx.read(datastoreType, path).checkedGet();
112         } catch (ReadFailedException e) {
113             LOG.warn("Failed to read InstanceIdentifier {} from {}", path, datastoreType, e);
114         } finally {
115             tx.close();
116         }
117         return result;
118     }
119
120     /**
121      * Retrieves the acl matching the key from the data store.
122      *
123      * @param broker the data broker
124      * @param aclKey the acl key
125      * @return the acl
126      */
127     public static Acl getAcl(DataBroker broker, String aclKey) {
128         Optional<Acl> optAcl = read(broker,
129             LogicalDatastoreType.CONFIGURATION, getAclInstanceIdentifier(aclKey));
130         if (optAcl.isPresent()) {
131             return optAcl.get();
132         }
133         return null;
134     }
135
136     /** Creates the Acl instance identifier.
137      *
138      * @param aclKey the acl key
139      * @return the instance identifier
140      */
141     public static InstanceIdentifier<Acl> getAclInstanceIdentifier(String aclKey) {
142         return InstanceIdentifier
143                 .builder(AccessLists.class)
144                 .child(Acl.class,
145                         new AclKey(aclKey,Ipv4Acl.class))
146                 .build();
147     }
148
149     /**
150      * Get the data path number for the interface.
151      * @param interfaceManagerRpcService interfaceManagerRpcService instance.
152      * @param ifName the interface name.
153      * @return the dpn.
154      */
155     public static BigInteger getDpnForInterface(OdlInterfaceRpcService interfaceManagerRpcService, String ifName) {
156         BigInteger nodeId = BigInteger.ZERO;
157         try {
158             GetDpidFromInterfaceInput dpIdInput =
159                     new GetDpidFromInterfaceInputBuilder().setIntfName(ifName).build();
160             Future<RpcResult<GetDpidFromInterfaceOutput>> dpIdOutput =
161                     interfaceManagerRpcService.getDpidFromInterface(dpIdInput);
162             RpcResult<GetDpidFromInterfaceOutput> dpIdResult = dpIdOutput.get();
163             if (dpIdResult.isSuccessful()) {
164                 nodeId = dpIdResult.getResult().getDpid();
165             } else {
166                 LOG.error("Could not retrieve DPN Id for interface {}", ifName);
167             }
168         } catch (NullPointerException | InterruptedException | ExecutionException e) {
169             LOG.error("Exception when getting dpn for interface {}", ifName,  e);
170         }
171         return nodeId;
172     }
173
174     /**
175      * Retrieves the interface state.
176      * @param dataBroker the data broker.
177      * @param interfaceName the interface name.
178      * @return the interface state.
179      */
180     public static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state
181         .Interface getInterfaceStateFromOperDS(DataBroker dataBroker, String interfaceName) {
182         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
183             .interfaces.state.Interface> ifStateId = buildStateInterfaceId(interfaceName);
184         Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
185             .interfaces.state.Interface> ifStateOptional = MDSALUtil.read(LogicalDatastoreType
186                 .OPERATIONAL, ifStateId, dataBroker);
187         if (!ifStateOptional.isPresent()) {
188             return null;
189         }
190
191         return ifStateOptional.get();
192     }
193
194     /**
195      * Build the interface state.
196      * @param interfaceName the interface name.
197      * @return the interface state.
198      */
199     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
200         .interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
201         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
202             .interfaces.state.Interface> idBuilder = InstanceIdentifier.builder(InterfacesState.class)
203             .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
204             .state.Interface.class, new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces
205             .rev140508.interfaces.state.InterfaceKey(interfaceName));
206         return idBuilder.build();
207     }
208
209     /**
210      * Checks whether port security is enabled for the port.
211      * @param port the port.
212      * @return the port security is enabled/not.
213      */
214     public static boolean isPortSecurityEnabled(Interface port) {
215         if (port == null) {
216             LOG.error("Port is Null");
217             return false;
218         }
219         InterfaceAcl aclInPort = port.getAugmentation(InterfaceAcl.class);
220         if (aclInPort == null) {
221             LOG.error("getSecurityGroupInPortList: no security group associated to Interface port: {}", port.getName());
222             return false;
223         }
224         return aclInPort.isPortSecurityEnabled();
225     }
226
227     /**
228      * Checks whether port security is enabled for the port.
229      * @param port the port.
230      * @return the list of security groups.
231      */
232     public static List<Uuid> getInterfaceAcls(Interface port) {
233         if (port == null) {
234             LOG.error("Port is Null");
235             return null;
236         }
237         InterfaceAcl aclInPort = port.getAugmentation(InterfaceAcl.class);
238         if (aclInPort == null) {
239             LOG.error("getSecurityGroupInPortList: no security group associated}",
240                 port.getName());
241             return null;
242         }
243         return aclInPort.getSecurityGroups();
244     }
245
246     /**
247      * Retrieves the security rule attribute augmentation from the access list.
248      * @param ace the access list entry
249      * @return the security rule attributes
250      */
251     public static SecurityRuleAttr  getAccesssListAttributes(Ace ace) {
252         if (ace == null) {
253             LOG.error("Ace is Null");
254             return null;
255         }
256         SecurityRuleAttr aceAttributes = ace.getAugmentation(SecurityRuleAttr.class);
257         if (aceAttributes == null) {
258             LOG.error("Ace is null");
259             return null;
260         }
261         return aceAttributes;
262     }
263
264     /**
265      * Returns the DHCP match.
266      * @param srcPort the source port.
267      * @param dscPort the destination port.
268      * @return list of matches.
269      */
270     public static List<MatchInfoBase> programDhcpMatches(int srcPort, int dscPort) {
271         List<MatchInfoBase> matches = new ArrayList<>();
272         matches.add(new MatchInfo(MatchFieldType.eth_type,
273                 new long[] { NwConstants.ETHTYPE_IPV4 }));
274         matches.add(new MatchInfo(MatchFieldType.ip_proto,
275                 new long[] { IPProtocols.UDP.intValue() }));
276         matches.add(new MatchInfo(MatchFieldType.udp_dst,
277                 new long[] { srcPort }));
278         matches.add(new MatchInfo(MatchFieldType.udp_src,
279                 new long[] { dscPort}));
280         return matches;
281     }
282
283     /**
284      * Builds the service id.
285      *
286      * @param interfaceName the interface name
287      * @param serviceIndex the service index
288      * @param serviceMode the service mode
289      * @return the instance identifier
290      */
291     public static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short serviceIndex,
292             Class<? extends ServiceModeBase> serviceMode) {
293         return InstanceIdentifier.builder(ServiceBindings.class)
294                 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, serviceMode))
295                 .child(BoundServices.class, new BoundServicesKey(serviceIndex)).build();
296     }
297
298     /**
299      * Gets the bound services.
300      *
301      * @param serviceName the service name
302      * @param servicePriority the service priority
303      * @param flowPriority the flow priority
304      * @param cookie the cookie
305      * @param instructions the instructions
306      * @return the bound services
307      */
308     public static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
309             BigInteger cookie, List<Instruction> instructions) {
310         StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
311                 .setInstruction(instructions);
312         return new BoundServicesBuilder().setKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
313                 .setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
314                 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
315     }
316
317     public static List<Uuid> getUpdatedAclList(Interface updatedPort, Interface currentPort) {
318         if (updatedPort == null) {
319             return null;
320         }
321         List<Uuid> updatedAclList = new ArrayList<>(AclServiceUtils.getInterfaceAcls(updatedPort));
322         if (currentPort == null) {
323             return updatedAclList;
324         }
325         List<Uuid> currentAclList = new ArrayList<>(AclServiceUtils.getInterfaceAcls(currentPort));
326         for (Iterator<Uuid> iterator = updatedAclList.iterator(); iterator.hasNext();) {
327             Uuid updatedAclUuid = iterator.next();
328             for (Uuid currentAclUuid :currentAclList) {
329                 if (updatedAclUuid.getValue().equals(currentAclUuid.getValue())) {
330                     iterator.remove();
331                 }
332             }
333         }
334         return updatedAclList;
335     }
336
337     public static List<AllowedAddressPairs> getUpdatedAllowedAddressPairs(Interface updatedPort,
338             Interface currentPort) {
339         if (updatedPort == null) {
340             return null;
341         }
342         List<AllowedAddressPairs> updatedAllowedAddressPairs =
343                 new ArrayList<>(AclServiceUtils.getPortAllowedAddresses(updatedPort));
344         if (currentPort == null) {
345             return updatedAllowedAddressPairs;
346         }
347         List<AllowedAddressPairs> currentAllowedAddressPairs =
348                 new ArrayList<>(AclServiceUtils.getPortAllowedAddresses(currentPort));
349         for (Iterator<AllowedAddressPairs> iterator = updatedAllowedAddressPairs.iterator(); iterator.hasNext();) {
350             AllowedAddressPairs updatedAllowedAddressPair = iterator.next();
351             for (AllowedAddressPairs currentAllowedAddressPair : currentAllowedAddressPairs) {
352                 if (updatedAllowedAddressPair.getKey().equals(currentAllowedAddressPair.getKey())) {
353                     iterator.remove();
354                     break;
355                 }
356             }
357         }
358         return updatedAllowedAddressPairs;
359     }
360
361     public static List<AllowedAddressPairs> getPortAllowedAddresses(Interface port) {
362         if (port == null) {
363             LOG.error("Port is Null");
364             return null;
365         }
366         InterfaceAcl aclInPort = port.getAugmentation(InterfaceAcl.class);
367         if (aclInPort == null) {
368             LOG.error("getSecurityGroupInPortList: no security group associated to Interface port: {}", port.getName());
369             return null;
370         }
371         return aclInPort.getAllowedAddressPairs();
372     }
373
374     public static BigInteger getDpIdFromIterfaceState(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf
375             .interfaces.rev140508.interfaces.state.Interface interfaceState) {
376         BigInteger dpId = null;
377         String interfaceName = interfaceState.getName();
378         List<String> ofportIds = interfaceState.getLowerLayerIf();
379         if (ofportIds != null && !ofportIds.isEmpty()) {
380             NodeConnectorId nodeConnectorId = new NodeConnectorId(ofportIds.get(0));
381             dpId = BigInteger.valueOf(MDSALUtil.getDpnIdFromPortName(nodeConnectorId));
382         }
383         return dpId;
384     }
385
386     public static List<MatchInfoBase> getAllowedIpMatches(IpPrefixOrAddress allowedIp, MatchFieldType ipv4MatchType) {
387         List<MatchInfoBase> flowMatches = new ArrayList<>();
388         flowMatches.add(new MatchInfo(MatchFieldType.eth_type, new long[] { NwConstants.ETHTYPE_IPV4 }));
389         IpPrefix ipPrefix = allowedIp.getIpPrefix();
390         if (ipPrefix != null) {
391             if (ipPrefix.getIpv4Prefix().getValue() != null) {
392                 String[] ipaddressValues = ipPrefix.getIpv4Prefix().getValue().split("/");
393                 flowMatches.add(new MatchInfo(ipv4MatchType, new String[] {ipaddressValues[0], ipaddressValues[1]}));
394             } else {
395                 // Handle IPv6
396             }
397         } else {
398             IpAddress ipAddress = allowedIp.getIpAddress();
399             if (ipAddress.getIpv4Address() != null) {
400                 flowMatches.add(new MatchInfo(ipv4MatchType,
401                         new String[] {ipAddress.getIpv4Address().getValue(), "32"}));
402             } else {
403                 // Handle IPv6
404             }
405         }
406         return flowMatches;
407     }
408
409     public static List<MatchInfo> getLPortTagMatches(int lportTag) {
410         List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
411         // Matching metadata
412         mkMatches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
413             MetaDataUtil.getLportTagMetaData(lportTag),
414             MetaDataUtil.METADATA_MASK_LPORT_TAG }));
415         mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {BigInteger.valueOf(lportTag)}));
416         return mkMatches;
417     }
418 }