383c2e67982436113a6eb61f41a3d636a7cca9a4
[netvirt.git] / fibmanager / api / src / main / java / org / opendaylight / netvirt / fibmanager / api / FibHelper.java
1 /*
2  * Copyright (c) 2017 Ericsson India Global Services Pvt Ltd. 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.fibmanager.api;
10
11 import static java.util.Comparator.comparing;
12 import static java.util.stream.Collectors.toList;
13
14 import java.math.BigInteger;
15 import java.net.InetAddress;
16 import java.net.UnknownHostException;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.List;
20 import java.util.concurrent.ExecutionException;
21 import java.util.stream.Collectors;
22 import javax.annotation.Nullable;
23 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
24 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.FibEntries;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTables;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTablesKey;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntry;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntryBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntryKey;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentrybase.RoutePaths;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentrybase.RoutePathsBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentrybase.RoutePathsKey;
35 import org.opendaylight.yangtools.yang.binding.DataObject;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
38
39 public final class FibHelper {
40
41     private FibHelper() { }
42
43     public static RoutePaths buildRoutePath(String nextHop, Long label) {
44         RoutePathsBuilder builder = new RoutePathsBuilder()
45                 .withKey(new RoutePathsKey(nextHop))
46                 .setNexthopAddress(nextHop);
47         if (label != null) {
48             builder.setLabel(label);
49         }
50         return builder.build();
51     }
52
53     public static VrfEntryBuilder getVrfEntryBuilder(String prefix, RouteOrigin origin, @Nullable String parentVpnRd) {
54         return new VrfEntryBuilder().withKey(new VrfEntryKey(prefix)).setDestPrefix(prefix)
55                 .setOrigin(origin.getValue()).setParentVpnRd(parentVpnRd);
56     }
57
58     public static VrfEntryBuilder getVrfEntryBuilder(String prefix, List<RoutePaths> routePaths,
59             RouteOrigin origin, @Nullable String parentVpnRd) {
60         return new VrfEntryBuilder().withKey(new VrfEntryKey(prefix)).setDestPrefix(prefix)
61                 .setRoutePaths(routePaths).setOrigin(origin.getValue()).setParentVpnRd(parentVpnRd);
62     }
63
64     public static VrfEntryBuilder getVrfEntryBuilder(String prefix, long label, String nextHop, RouteOrigin origin,
65             @Nullable String parentVpnRd) {
66         if (nextHop != null) {
67             RoutePaths routePath = buildRoutePath(nextHop, label);
68             return getVrfEntryBuilder(prefix, Collections.singletonList(routePath), origin, parentVpnRd);
69         } else {
70             return getVrfEntryBuilder(prefix, origin, parentVpnRd);
71         }
72     }
73
74     public static VrfEntryBuilder getVrfEntryBuilder(VrfEntry vrfEntry, long label,
75             List<String> nextHopList, RouteOrigin origin, @Nullable String parentvpnRd) {
76         List<RoutePaths> routePaths =
77                 nextHopList.stream().map(nextHop -> buildRoutePath(nextHop, label))
78                         .collect(toList());
79         return getVrfEntryBuilder(vrfEntry.getDestPrefix(), routePaths, origin, parentvpnRd);
80     }
81
82     public static InstanceIdentifier<RoutePaths> buildRoutePathId(String rd, String prefix, String nextHop) {
83         InstanceIdentifierBuilder<RoutePaths> idBuilder =
84                 InstanceIdentifier.builder(FibEntries.class)
85                         .child(VrfTables.class, new VrfTablesKey(rd))
86                         .child(VrfEntry.class, new VrfEntryKey(prefix))
87                         .child(RoutePaths.class, new RoutePathsKey(nextHop));
88         return idBuilder.build();
89     }
90
91     public static boolean isControllerManagedNonInterVpnLinkRoute(RouteOrigin routeOrigin) {
92         return routeOrigin == RouteOrigin.STATIC
93                 || routeOrigin == RouteOrigin.CONNECTED
94                 || routeOrigin == RouteOrigin.LOCAL;
95     }
96
97     public static boolean isControllerManagedVpnInterfaceRoute(RouteOrigin routeOrigin) {
98         return routeOrigin == RouteOrigin.STATIC
99                 || routeOrigin == RouteOrigin.LOCAL;
100     }
101
102     public static boolean isControllerManagedNonSelfImportedRoute(RouteOrigin routeOrigin) {
103         return routeOrigin != RouteOrigin.SELF_IMPORTED;
104     }
105
106     public static void sortIpAddress(List<RoutePaths> routePathList) {
107         if (routePathList != null) {
108             routePathList.sort(comparing(RoutePaths::getNexthopAddress));
109         }
110     }
111
112     public static List<String> getNextHopListFromRoutePaths(final VrfEntry vrfEntry) {
113         List<RoutePaths> routePaths = vrfEntry.getRoutePaths();
114         if (routePaths == null || routePaths.isEmpty()) {
115             return new ArrayList<>();
116         }
117         return routePaths.stream()
118                 .map(RoutePaths::getNexthopAddress)
119                 .collect(Collectors.toList());
120     }
121
122     public static com.google.common.base.Optional<VrfEntry> getVrfEntry(DataBroker broker, String rd, String ipPrefix) {
123         InstanceIdentifier<VrfEntry> vrfEntryId = InstanceIdentifier.builder(FibEntries.class)
124             .child(VrfTables.class, new VrfTablesKey(rd))
125             .child(VrfEntry.class, new VrfEntryKey(ipPrefix)).build();
126         return read(broker, LogicalDatastoreType.CONFIGURATION, vrfEntryId);
127     }
128
129     private static <T extends DataObject> com.google.common.base.Optional<T> read(DataBroker broker,
130             LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
131         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
132             return tx.read(datastoreType, path).get();
133         } catch (InterruptedException | ExecutionException e) {
134             throw new RuntimeException(e);
135         }
136     }
137
138     /** get true if this prefix is an IPv4 version, false otherwise.
139      * @param prefix the prefix as (x.x.x.x/nn) to find if it is in IP version 4
140      * @return true if it is an IPv4 or false if it is not.
141      */
142     public static boolean isIpv4Prefix(String prefix) {
143         if (prefix == null || prefix.length() < 7) {
144             return false;
145         }
146         try {
147             String ip = getIpFromPrefix(prefix);
148             java.net.Inet4Address.getByName(ip);
149         } catch (SecurityException | UnknownHostException | ClassCastException e) {
150             return false;
151         }
152         return true;
153     }
154
155     /** get true if this prefix is an IPv6 version, false otherwise.
156      * @param prefix the prefix as ( x:x:x::/nn) to find if it is in IP version 6
157      * @return true if it is an IPv4 or false if it is not.
158      */
159     public static boolean isIpv6Prefix(String prefix) {
160         if (prefix == null || prefix.length() < 2) {
161             return false;
162         }
163         try {
164             String ip = getIpFromPrefix(prefix);
165             java.net.Inet6Address.getByName(ip);
166         } catch (SecurityException | UnknownHostException | ClassCastException e) {
167             return false;
168         }
169         return true;
170     }
171
172     /**get String format IP from prefix as x.x.....x/nn.
173      * @param prefix the prefix as IPv4 or IPv6 as x.....x/nn
174      * @return prefix if "/" is unfindable or the IP only as x.x...x from x.x......x/nn
175      */
176     @Nullable
177     public static String getIpFromPrefix(String prefix) {
178         if (prefix == null || prefix.length() < 2) {
179             return null;
180         }
181         String rep = prefix;
182         String[] prefixValues = prefix.split("/");
183         if (prefixValues.length > 0) {
184             rep = prefixValues[0];
185         }
186         return rep;
187     }
188
189     /**Return true if this prefix or subnet is belonging the specified subnetwork.
190      * @param prefixToTest the prefix which could be in the subnet
191      * @param subnet the subnet that have to contain the prefixToTest to return true
192      * @return true if the param subnet contained the prefixToTest false otherwise
193      */
194     public static boolean isBelongingPrefix(String prefixToTest, String subnet) {
195         return doesPrefixBelongToSubnet(prefixToTest, subnet, true);
196     }
197
198     /**Return true if this prefix or subnet is belonging the specified subnetwork.
199      * @param prefixToTest the prefix which could be in the subnet
200      * @param subnet the subnet that have to contain the prefixToTest to return true
201      * @param exactMatch boolean set to true if exact match is expected
202      * @return true if the param subnet contained the prefixToTest false otherwise
203      */
204     public static boolean doesPrefixBelongToSubnet(String prefixToTest, String subnet, boolean exactMatch) {
205         if (prefixToTest == null || prefixToTest.length() < 7 || subnet == null || subnet.length() < 7) {
206             return false;
207         }
208         if (isIpv4Prefix(prefixToTest) && isIpv4Prefix(subnet)
209                 || isIpv6Prefix(prefixToTest) && isIpv6Prefix(subnet)) {
210
211             int ipVersion = 4;
212             if (isIpv6Prefix(prefixToTest)) {
213                 ipVersion = 6;
214             }
215
216             String ipPref = getIpFromPrefix(prefixToTest);
217             String ipSub = getIpFromPrefix(subnet);
218             String maskSubString = subnet.substring(subnet.indexOf("/") + 1);
219             String maskPrefString;
220             if (prefixToTest.contains("/")) {
221                 maskPrefString = prefixToTest.substring(prefixToTest.indexOf("/") + 1);
222             } else if (ipVersion == 4) {
223                 maskPrefString = "32";
224             } else {
225                 maskPrefString = "128";
226             }
227
228             try {
229                 int maskPref = Integer.parseInt(maskPrefString);
230                 int maskSub = Integer.parseInt(maskSubString);
231                 if (exactMatch && maskPref != maskSub) {
232                  /*because the mask must be exactly the same between them, the return type is false. This behavior could
233                   * be changed to ignored it in including a boolean options to force or not the same mask control*/
234                     return false;
235                 }
236                 BigInteger maskSubBig = getMaskNetwork(ipVersion, maskSub);
237                 byte[] byteIpSub = InetAddress.getByName(ipSub).getAddress();
238                 byte[] byteIpPref = InetAddress.getByName(ipPref).getAddress();
239                 BigInteger netFromIpSub = packBigInteger(byteIpSub).and(maskSubBig);
240                 BigInteger netFromIpPref = packBigInteger(byteIpPref).and(maskSubBig);
241                 return netFromIpSub.compareTo(netFromIpPref) == 0;
242             } catch (NumberFormatException | UnknownHostException e) {
243                 return false;
244             }
245         }
246         return false;
247     }
248
249     /**This method converts a byte[] to a BigInteger value.
250      * @param bytes the byte[] of IP
251      * @return (big) integer value of IP_bytes
252      */
253     public static BigInteger packBigInteger(byte[] bytes) {
254         BigInteger val = BigInteger.valueOf(0);
255         for (byte b : bytes) {
256             val = val.shiftLeft(8);
257             val = val.add(BigInteger.valueOf(b & 0xff));
258         }
259         return val;
260     }
261
262     /**get the bits cache mask of net for a ip version type.
263      * @param ipVersion version of ip must be 4 or 6
264      * @param mask the lengh of the mask of net as 24 from this representation 10.1.1.0/24 or 64 for 2001::1/64
265      * @return the bit mask of net ex: x.x.x.x/24 return a BigInteger == 0xFFFFFFotherwise null if any error
266      */
267     @Nullable
268     public static BigInteger getMaskNetwork(int ipVersion, int mask) {
269         int lenghBitsIp = 0;
270         if (ipVersion == 6) {
271             lenghBitsIp = 128 - 1;
272         } else if (ipVersion == 4) {
273             lenghBitsIp = 32 - 1;
274         } else {
275             return null;//ip version is unknown
276         }
277         BigInteger bb = BigInteger.ZERO;
278         for (int i = 0 ; i < mask; i++) {
279             bb = bb.setBit(lenghBitsIp - i);
280         }
281         return bb;
282     }
283 }