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