deprecate ItmUtils' read() and write() methods
[genius.git] / itm / itm-impl / src / main / java / org / opendaylight / genius / itm / impl / ItmUtils.java
1 /*
2  * Copyright © 2016, 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.genius.itm.impl;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.BiMap;
13 import com.google.common.collect.ImmutableBiMap;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.net.InetAddresses;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import java.math.BigInteger;
20 import java.net.InetAddress;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.UUID;
27 import java.util.concurrent.ExecutionException;
28 import javax.annotation.Nonnull;
29 import org.apache.commons.lang3.StringUtils;
30 import org.apache.commons.net.util.SubnetUtils;
31 import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
32 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
33 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
34 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
35 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
36 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
37 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
38 import org.opendaylight.genius.interfacemanager.globals.IfmConstants;
39 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
40 import org.opendaylight.genius.itm.api.IITMProvider;
41 import org.opendaylight.genius.itm.cache.DPNTEPsInfoCache;
42 import org.opendaylight.genius.itm.confighelpers.HwVtep;
43 import org.opendaylight.genius.itm.confighelpers.ItmTunnelAggregationHelper;
44 import org.opendaylight.genius.itm.globals.ITMConstants;
45 import org.opendaylight.genius.mdsalutil.ActionInfo;
46 import org.opendaylight.genius.mdsalutil.FlowEntity;
47 import org.opendaylight.genius.mdsalutil.InstructionInfo;
48 import org.opendaylight.genius.mdsalutil.MDSALUtil;
49 import org.opendaylight.genius.mdsalutil.MatchInfo;
50 import org.opendaylight.genius.mdsalutil.NwConstants;
51 import org.opendaylight.genius.mdsalutil.actions.ActionPuntToController;
52 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
53 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
54 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.Tunnel;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
59 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefixBuilder;
60 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType;
61 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
62 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
63 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
64 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
65 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlan;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlanBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnelBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefsBuilder;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelMonitoringTypeBase;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeGre;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeLogicalGroup;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeMplsOverGre;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifier;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierKey;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.tunnel.optional.params.TunnelOptions;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.tunnel.optional.params.TunnelOptionsBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.tunnel.optional.params.TunnelOptionsKey;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.ItmConfig;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.VtepConfigSchemas;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.VtepIpPools;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchema;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaBuilder;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaKey;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIds;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsKey;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPool;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPoolKey;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpoints;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpointsBuilder;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeBase;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeExternal;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeHwvtep;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeInternal;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelList;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelOperStatus;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelsState;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfo;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoBuilder;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoKey;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPoints;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsBuilder;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsKey;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.tunnel.end.points.TzMembership;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.tunnel.end.points.TzMembershipBuilder;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelBuilder;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnel;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelBuilder;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelKey;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.StateTunnelList;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.StateTunnelListBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.StateTunnelListKey;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.state.tunnel.list.DstInfoBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.state.tunnel.list.SrcInfoBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.DcGatewayIpList;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.TransportZones;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.dc.gateway.ip.list.DcGatewayIp;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TepsNotHostedInTransportZone;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TepsNotHostedInTransportZoneKey;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZone;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZoneKey;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.Subnets;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.subnets.Vteps;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
135 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
136 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
137 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
138 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
139 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
140 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
141 import org.opendaylight.yangtools.yang.binding.DataObject;
142 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
143 import org.slf4j.Logger;
144 import org.slf4j.LoggerFactory;
145
146 public final class ItmUtils {
147
148     private static final Logger LOG = LoggerFactory.getLogger(ItmUtils.class);
149
150     private static final String TUNNEL = "tun";
151     private static final IpPrefix DUMMY_IP_PREFIX = IpPrefixBuilder.getDefaultInstance(ITMConstants.DUMMY_PREFIX);
152     private static final long DEFAULT_MONITORING_INTERVAL = 100L;
153     public static final ItmCache ITM_CACHE = new ItmCache();
154
155     public static final ImmutableMap<String, Class<? extends TunnelTypeBase>>
156             TUNNEL_TYPE_MAP =
157             new ImmutableMap.Builder<String, Class<? extends TunnelTypeBase>>()
158                     .put(ITMConstants.TUNNEL_TYPE_GRE, TunnelTypeGre.class)
159                     .put(ITMConstants.TUNNEL_TYPE_MPLSoGRE, TunnelTypeMplsOverGre.class)
160                     .put(ITMConstants.TUNNEL_TYPE_VXLAN, TunnelTypeVxlan.class)
161                     .build();
162
163     private static final BiMap<String,Class<? extends TunnelTypeBase>> STRING_CLASS_IMMUTABLE_BI_MAP =
164             ImmutableBiMap.copyOf(TUNNEL_TYPE_MAP);
165
166     private ItmUtils() {
167     }
168
169     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
170         @Override
171         public void onSuccess(Void result) {
172             LOG.debug("Success in Datastore write operation");
173         }
174
175         @Override
176         public void onFailure(@Nonnull Throwable error) {
177             LOG.error("Error in Datastore write operation", error);
178         }
179     };
180
181     /**
182      * Synchronous blocking read from data store.
183      *
184      * @deprecated Use
185      * {@link SingleTransactionDataBroker#syncReadOptional(DataBroker, LogicalDatastoreType, InstanceIdentifier)}
186      *             instead of this.
187      */
188     @Deprecated
189     @SuppressWarnings("checkstyle:IllegalCatch")
190     public static <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
191                                                           InstanceIdentifier<T> path, DataBroker broker) {
192         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
193             return tx.read(datastoreType, path).get();
194         } catch (Exception e) {
195             throw new RuntimeException(e);
196         }
197     }
198
199     public static <T extends DataObject> void asyncWrite(LogicalDatastoreType datastoreType,
200                                                          InstanceIdentifier<T> path, T data, DataBroker broker,
201                                                          FutureCallback<Void> callback) {
202         WriteTransaction tx = broker.newWriteOnlyTransaction();
203         tx.put(datastoreType, path, data, true);
204         Futures.addCallback(tx.submit(), callback);
205     }
206
207     public static <T extends DataObject> void asyncUpdate(LogicalDatastoreType datastoreType,
208                                                           InstanceIdentifier<T> path, T data, DataBroker broker,
209                                                           FutureCallback<Void> callback) {
210         WriteTransaction tx = broker.newWriteOnlyTransaction();
211         tx.merge(datastoreType, path, data, true);
212         Futures.addCallback(tx.submit(), callback);
213     }
214
215     public static <T extends DataObject> void asyncDelete(LogicalDatastoreType datastoreType,
216                                                           InstanceIdentifier<T> path, DataBroker broker,
217                                                           FutureCallback<Void> callback) {
218         WriteTransaction tx = broker.newWriteOnlyTransaction();
219         tx.delete(datastoreType, path);
220         Futures.addCallback(tx.submit(), callback);
221     }
222
223     public static <T extends DataObject> void asyncBulkRemove(final DataBroker broker,
224                                                               final LogicalDatastoreType datastoreType,
225                                                               List<InstanceIdentifier<T>> pathList,
226                                                               FutureCallback<Void> callback) {
227         if (!pathList.isEmpty()) {
228             WriteTransaction tx = broker.newWriteOnlyTransaction();
229             for (InstanceIdentifier<T> path : pathList) {
230                 tx.delete(datastoreType, path);
231             }
232             Futures.addCallback(tx.submit(), callback);
233         }
234     }
235
236     public static String getInterfaceName(final BigInteger datapathid, final String portName, final Integer vlanId) {
237         return String.format("%s:%s:%s", datapathid, portName, vlanId);
238     }
239
240     public static BigInteger getDpnIdFromInterfaceName(String interfaceName) {
241         String[] dpnStr = interfaceName.split(":");
242         return new BigInteger(dpnStr[0]);
243     }
244
245     public static String getTrunkInterfaceName(String parentInterfaceName,
246                                                String localHostName, String remoteHostName, String tunnelType) {
247         String tunnelTypeStr;
248         if (tunnelType.contains("TunnelTypeGre")) {
249             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_GRE;
250         } else if (tunnelType.contains("TunnelTypeLogicalGroup")) {
251             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_LOGICAL_GROUP_VXLAN;
252         } else {
253             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_VXLAN;
254         }
255         String trunkInterfaceName = String.format("%s:%s:%s:%s", parentInterfaceName, localHostName,
256                 remoteHostName, tunnelTypeStr);
257         LOG.trace("trunk interface name is {}", trunkInterfaceName);
258         trunkInterfaceName = String.format("%s%s", TUNNEL, getUniqueIdString(trunkInterfaceName));
259         return trunkInterfaceName;
260     }
261
262     public static void releaseIdForTrunkInterfaceName(String parentInterfaceName,
263                                                       String localHostName, String remoteHostName, String tunnelType) {
264         String tunnelTypeStr;
265         if (tunnelType.contains("TunnelTypeGre")) {
266             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_GRE;
267         } else {
268             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_VXLAN;
269         }
270         String trunkInterfaceName = String.format("%s:%s:%s:%s", parentInterfaceName, localHostName,
271                 remoteHostName, tunnelTypeStr);
272         LOG.trace("Releasing Id for trunkInterface - {}", trunkInterfaceName);
273     }
274
275     public static String getLogicalTunnelGroupName(BigInteger srcDpnId, BigInteger destDpnId) {
276         String tunnelTypeStr = ITMConstants.TUNNEL_TYPE_LOGICAL_GROUP_VXLAN;
277         String groupName = String.format("%s:%s:%s", srcDpnId.toString(), destDpnId.toString(), tunnelTypeStr);
278         LOG.trace("logical tunnel group name is {}", groupName);
279         groupName = String.format("%s%s", TUNNEL, getUniqueIdString(groupName));
280         return groupName;
281     }
282
283     public static InetAddress getInetAddressFromIpAddress(IpAddress ip) {
284         return InetAddresses.forString(String.valueOf(ip.getValue()));
285     }
286
287     public static InstanceIdentifier<DPNTEPsInfo> getDpnTepInstance(BigInteger dpIdKey) {
288         return InstanceIdentifier.builder(DpnEndpoints.class).child(DPNTEPsInfo.class, new DPNTEPsInfoKey(dpIdKey))
289                 .build();
290     }
291
292     public static DPNTEPsInfo createDPNTepInfo(BigInteger dpId, List<TunnelEndPoints> endpoints) {
293         return new DPNTEPsInfoBuilder().setKey(new DPNTEPsInfoKey(dpId)).setTunnelEndPoints(endpoints).build();
294     }
295
296     public static TunnelEndPoints createTunnelEndPoints(BigInteger dpnId, IpAddress ipAddress, String portName,
297                                                         boolean isOfTunnel, int vlanId, IpPrefix prefix,
298                                                         IpAddress gwAddress, List<TzMembership> zones,
299                                                         Class<? extends TunnelTypeBase>  tunnelType,
300                                                         String tos) {
301         // when Interface Mgr provides support to take in Dpn Id
302         return new TunnelEndPointsBuilder().setKey(new TunnelEndPointsKey(ipAddress, portName,tunnelType, vlanId))
303                 .setSubnetMask(prefix).setGwIpAddress(gwAddress).setTzMembership(zones)
304                 .setOptionOfTunnel(isOfTunnel).setInterfaceName(ItmUtils.getInterfaceName(dpnId, portName, vlanId))
305                 .setTunnelType(tunnelType)
306                 .setOptionTunnelTos(tos)
307                 .build();
308     }
309
310     public static DpnEndpoints createDpnEndpoints(List<DPNTEPsInfo> dpnTepInfo) {
311         return new DpnEndpointsBuilder().setDPNTEPsInfo(dpnTepInfo).build();
312     }
313
314     public static InstanceIdentifier<Interface> buildId(String interfaceName) {
315         return InstanceIdentifier.builder(Interfaces.class).child(Interface.class, new InterfaceKey(interfaceName))
316                 .build();
317     }
318
319     public static InstanceIdentifier<IfTunnel> buildTunnelId(String ifName) {
320         return InstanceIdentifier.builder(Interfaces.class)
321                 .child(Interface.class, new InterfaceKey(ifName)).augmentation(IfTunnel.class).build();
322     }
323
324     public static Interface buildLogicalTunnelInterface(BigInteger dpn, String ifName, String desc, boolean enabled) {
325         InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(ifName)).setName(ifName)
326                 .setDescription(desc).setEnabled(enabled).setType(Tunnel.class);
327         ParentRefs parentRefs = new ParentRefsBuilder().setDatapathNodeIdentifier(dpn).build();
328         builder.addAugmentation(ParentRefs.class, parentRefs);
329
330         IfTunnel tunnel = new IfTunnelBuilder()
331                 .setTunnelDestination(IpAddressBuilder.getDefaultInstance(ITMConstants.DUMMY_IP_ADDRESS))
332                 .setTunnelSource(IpAddressBuilder.getDefaultInstance(ITMConstants.DUMMY_IP_ADDRESS)).setInternal(true)
333                 .setMonitorEnabled(false).setTunnelInterfaceType(TunnelTypeLogicalGroup.class)
334                 .setTunnelRemoteIpFlow(false).build();
335         builder.addAugmentation(IfTunnel.class, tunnel);
336         return builder.build();
337     }
338
339     public static Interface buildTunnelInterface(BigInteger dpn, String ifName, String desc, boolean enabled,
340                                                  Class<? extends TunnelTypeBase> tunType, IpAddress localIp,
341                                                  IpAddress remoteIp, IpAddress gatewayIp, Integer vlanId,
342                                                  boolean internal, Boolean monitorEnabled,
343                                                  Class<? extends TunnelMonitoringTypeBase> monitorProtocol,
344                                                  Integer monitorInterval, boolean useOfTunnel,
345                                                  List<TunnelOptions> tunOptions) {
346
347         return buildTunnelInterface(dpn, ifName, desc, enabled, tunType, localIp, remoteIp,  gatewayIp,  vlanId,
348                                     internal,  monitorEnabled, monitorProtocol, monitorInterval,  useOfTunnel, null,
349                                     tunOptions);
350     }
351
352     public static Interface buildTunnelInterface(BigInteger dpn, String ifName, String desc, boolean enabled,
353                                                  Class<? extends TunnelTypeBase> tunType, IpAddress localIp,
354                                                  IpAddress remoteIp, IpAddress gatewayIp, Integer vlanId,
355                                                  boolean internal, Boolean monitorEnabled,
356                                                  Class<? extends TunnelMonitoringTypeBase> monitorProtocol,
357                                                  Integer monitorInterval, boolean useOfTunnel, String parentIfaceName,
358                                                  List<TunnelOptions> tunnelOptions) {
359         InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(ifName)).setName(ifName)
360                 .setDescription(desc).setEnabled(enabled).setType(Tunnel.class);
361         ParentRefs parentRefs =
362                 new ParentRefsBuilder().setDatapathNodeIdentifier(dpn).setParentInterface(parentIfaceName).build();
363         builder.addAugmentation(ParentRefs.class, parentRefs);
364         Long monitoringInterval = null;
365         if (vlanId > 0) {
366             IfL2vlan l2vlan = new IfL2vlanBuilder().setVlanId(new VlanId(vlanId)).build();
367             builder.addAugmentation(IfL2vlan.class, l2vlan);
368         }
369         LOG.debug("buildTunnelInterface: monitorProtocol = {} and monitorInterval = {}",
370                 monitorProtocol.getName(),monitorInterval);
371
372         if (monitorInterval != null) {
373             monitoringInterval = monitorInterval.longValue();
374         }
375
376         IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(remoteIp).setTunnelGateway(gatewayIp)
377                 .setTunnelSource(localIp).setTunnelInterfaceType(tunType).setInternal(internal)
378                 .setMonitorEnabled(monitorEnabled).setMonitorProtocol(monitorProtocol)
379                 .setMonitorInterval(monitoringInterval).setTunnelRemoteIpFlow(useOfTunnel)
380                 .setTunnelOptions(tunnelOptions)
381                 .build();
382         builder.addAugmentation(IfTunnel.class, tunnel);
383         return builder.build();
384     }
385
386     public static Interface buildHwTunnelInterface(String tunnelIfName, String desc, boolean enabled, String topoId,
387                                                    String nodeId, Class<? extends TunnelTypeBase> tunType,
388                                                    IpAddress srcIp, IpAddress destIp, IpAddress gwIp,
389                                                    Boolean monitorEnabled,
390                                                    Class<? extends TunnelMonitoringTypeBase> monitorProtocol,
391                                                    Integer monitorInterval) {
392         InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(tunnelIfName))
393                 .setName(tunnelIfName).setDescription(desc).setEnabled(enabled).setType(Tunnel.class);
394         List<NodeIdentifier> nodeIds = new ArrayList<>();
395         NodeIdentifier hwNode = new NodeIdentifierBuilder().setKey(new NodeIdentifierKey(topoId))
396                 .setTopologyId(topoId).setNodeId(nodeId).build();
397         nodeIds.add(hwNode);
398         ParentRefs parent = new ParentRefsBuilder().setNodeIdentifier(nodeIds).build();
399         builder.addAugmentation(ParentRefs.class, parent);
400         IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(destIp).setTunnelGateway(gwIp)
401                 .setTunnelSource(srcIp).setMonitorEnabled(monitorEnabled == null || monitorEnabled)
402                 .setMonitorProtocol(monitorProtocol == null ? ITMConstants.DEFAULT_MONITOR_PROTOCOL : monitorProtocol)
403                 .setMonitorInterval(DEFAULT_MONITORING_INTERVAL).setTunnelInterfaceType(tunType).setInternal(false)
404                 .build();
405         builder.addAugmentation(IfTunnel.class, tunnel);
406         LOG.trace("iftunnel {} built from hwvtep {} ", tunnel, nodeId);
407         return builder.build();
408     }
409
410     public static InternalTunnel buildInternalTunnel(BigInteger srcDpnId, BigInteger dstDpnId,
411                                                      Class<? extends TunnelTypeBase> tunType,
412                                                      String trunkInterfaceName) {
413         return new InternalTunnelBuilder().setKey(new InternalTunnelKey(dstDpnId, srcDpnId, tunType))
414                 .setDestinationDPN(dstDpnId)
415                 .setSourceDPN(srcDpnId).setTransportType(tunType)
416                 .setTunnelInterfaceNames(Collections.singletonList(trunkInterfaceName)).build();
417     }
418
419     public static ExternalTunnel buildExternalTunnel(String srcNode, String dstNode,
420                                                      Class<? extends TunnelTypeBase> tunType,
421                                                      String trunkInterfaceName) {
422         return new ExternalTunnelBuilder().setKey(
423                 new ExternalTunnelKey(dstNode, srcNode, tunType))
424                 .setSourceDevice(srcNode).setDestinationDevice(dstNode)
425                 .setTunnelInterfaceName(trunkInterfaceName)
426                 .setTransportType(tunType).build();
427     }
428
429     private static String getUniqueIdString(String idKey) {
430         return UUID.nameUUIDFromBytes(idKey.getBytes(StandardCharsets.UTF_8)).toString().substring(0, 12)
431                 .replace("-", "");
432     }
433
434     public static List<DPNTEPsInfo> getDpnTepListFromDpnId(DPNTEPsInfoCache dpnTEPsInfoCache, List<BigInteger> dpnIds) {
435         Collection<DPNTEPsInfo> meshedDpnList = dpnTEPsInfoCache.getAllPresent();
436         List<DPNTEPsInfo> cfgDpnList = new ArrayList<>();
437         for (BigInteger dpnId : dpnIds) {
438             for (DPNTEPsInfo teps : meshedDpnList) {
439                 if (dpnId.equals(teps.getDPNID())) {
440                     cfgDpnList.add(teps);
441                 }
442             }
443         }
444
445         return cfgDpnList;
446     }
447
448     @SuppressWarnings("checkstyle:IllegalCatch")
449     public static void setUpOrRemoveTerminatingServiceTable(BigInteger dpnId, IMdsalApiManager mdsalManager,
450                                                             boolean addFlag) {
451         String logmsg = addFlag ? "Installing" : "Removing";
452         LOG.trace("{}PUNT to Controller flow in DPN {} ", logmsg, dpnId);
453         List<ActionInfo> listActionInfo = new ArrayList<>();
454         listActionInfo.add(new ActionPuntToController());
455
456         try {
457             List<MatchInfo> mkMatches = new ArrayList<>();
458
459             mkMatches.add(new MatchTunnelId(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)));
460
461             List<InstructionInfo> mkInstructions = new ArrayList<>();
462             mkInstructions.add(new InstructionApplyActions(listActionInfo));
463
464             FlowEntity terminatingServiceTableFlowEntity = MDSALUtil
465                     .buildFlowEntity(dpnId, NwConstants.INTERNAL_TUNNEL_TABLE,
466                             getFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, ITMConstants.LLDP_SERVICE_ID),
467                             5, String.format("%s:%d","ITM Flow Entry ", ITMConstants.LLDP_SERVICE_ID), 0, 0,
468                             ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)),
469                             mkMatches, mkInstructions);
470             if (addFlag) {
471                 mdsalManager.installFlow(terminatingServiceTableFlowEntity);
472             } else {
473                 mdsalManager.removeFlow(terminatingServiceTableFlowEntity);
474             }
475         } catch (Exception e) {
476             LOG.error("Error while setting up Table 36 for {}", dpnId, e);
477         }
478     }
479
480     private static String getFlowRef(long termSvcTable, int svcId) {
481         return String.valueOf(termSvcTable) + svcId;
482     }
483
484     public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier(String schemaName) {
485         return InstanceIdentifier.builder(VtepConfigSchemas.class)
486                 .child(VtepConfigSchema.class, new VtepConfigSchemaKey(schemaName)).build();
487     }
488
489     public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier() {
490         return InstanceIdentifier.builder(VtepConfigSchemas.class).child(VtepConfigSchema.class).build();
491     }
492
493     public static InstanceIdentifier<VtepConfigSchemas> getVtepConfigSchemasIdentifier() {
494         return InstanceIdentifier.builder(VtepConfigSchemas.class).build();
495     }
496
497     public static InstanceIdentifier<VtepIpPool> getVtepIpPoolIdentifier(String subnetCidr) {
498         return InstanceIdentifier.builder(VtepIpPools.class).child(VtepIpPool.class, new VtepIpPoolKey(subnetCidr))
499                 .build();
500     }
501
502     public static VtepConfigSchema validateForAddVtepConfigSchema(VtepConfigSchema schema,
503                                                                   List<VtepConfigSchema> existingSchemas) {
504         VtepConfigSchema validSchema = validateVtepConfigSchema(schema);
505         for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
506             if (!StringUtils.equalsIgnoreCase(schema.getSchemaName(), existingSchema.getSchemaName())
507                     && schema.getSubnet().equals(existingSchema.getSubnet())) {
508                 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
509                 Preconditions.checkArgument(false, "VTEP schema with subnet [" + subnetCidr
510                         + "] already exists. Multiple VTEP schemas with same subnet is not allowed.");
511             }
512         }
513         if (isNotEmpty(getDpnIdList(validSchema.getDpnIds()))) {
514             String tzone = validSchema.getTransportZoneName();
515             List<BigInteger> lstDpns = getConflictingDpnsAlreadyConfiguredWithTz(validSchema.getSchemaName(), tzone,
516                     getDpnIdList(validSchema.getDpnIds()), existingSchemas);
517             if (!lstDpns.isEmpty()) {
518                 Preconditions.checkArgument(false, "DPN's " + lstDpns + " already configured for transport zone "
519                                 + tzone + ". Only one end point per transport Zone per Dpn is allowed.");
520             }
521             if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
522                 validateForSingleGreTep(validSchema.getSchemaName(), getDpnIdList(validSchema.getDpnIds()),
523                         existingSchemas);
524             }
525         }
526         return validSchema;
527     }
528
529     private static void validateForSingleGreTep(String schemaName, List<BigInteger> lstDpnsForAdd,
530                                                 List<VtepConfigSchema> existingSchemas) {
531         for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
532             if (TunnelTypeGre.class.equals(existingSchema.getTunnelType())
533                     && !StringUtils.equalsIgnoreCase(schemaName, existingSchema.getSchemaName())) {
534                 List<BigInteger> lstConflictingDpns = new ArrayList<>(getDpnIdList(existingSchema.getDpnIds()));
535                 lstConflictingDpns.retainAll(emptyIfNull(lstDpnsForAdd));
536                 if (!lstConflictingDpns.isEmpty()) {
537                     String errMsg = "DPN's " + lstConflictingDpns
538                             + " already configured with GRE TEP. Mutiple GRE TEP's on a single DPN are not allowed.";
539                     Preconditions.checkArgument(false, errMsg);
540                 }
541             }
542         }
543     }
544
545     public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
546         Preconditions.checkNotNull(schema);
547         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
548         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
549         Preconditions.checkArgument(schema.getVlanId() >= 0 && schema.getVlanId() < 4095,
550                 "Invalid VLAN ID, range (0-4094)");
551         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
552         Preconditions.checkNotNull(schema.getSubnet());
553         String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
554         SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
555         IpAddress gatewayIp = schema.getGatewayIp();
556         if (gatewayIp != null) {
557             String strGatewayIp = String.valueOf(gatewayIp.getValue());
558             if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS) && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
559                 Preconditions.checkArgument(false, "Gateway IP address " + strGatewayIp
560                         + " is not in subnet range " + subnetCidr);
561             }
562         }
563         ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
564         return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
565     }
566
567     public static String validateTunnelType(String tunnelType) {
568         if (tunnelType == null) {
569             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
570         } else {
571             tunnelType = StringUtils.upperCase(tunnelType);
572             String error = "Invalid tunnel type. Valid values: "
573                     + ITMConstants.TUNNEL_TYPE_VXLAN + " | " + ITMConstants.TUNNEL_TYPE_GRE;
574             Preconditions.checkArgument(ITMConstants.TUNNEL_TYPE_VXLAN.equals(tunnelType)
575                     || ITMConstants.TUNNEL_TYPE_GRE.equals(tunnelType), error);
576         }
577         return tunnelType;
578     }
579
580     private static List<BigInteger> getConflictingDpnsAlreadyConfiguredWithTz(String schemaName, String tzone,
581                                                                               List<BigInteger> lstDpns,
582                                                                               List<VtepConfigSchema> existingSchemas) {
583         List<BigInteger> lstConflictingDpns = new ArrayList<>();
584         for (VtepConfigSchema schema : emptyIfNull(existingSchemas)) {
585             if (!StringUtils.equalsIgnoreCase(schemaName, schema.getSchemaName())
586                     && StringUtils.equals(schema.getTransportZoneName(), tzone)) {
587                 lstConflictingDpns = new ArrayList<>(getDpnIdList(schema.getDpnIds()));
588                 lstConflictingDpns.retainAll(lstDpns);
589                 if (!lstConflictingDpns.isEmpty()) {
590                     break;
591                 }
592             }
593         }
594         return lstConflictingDpns;
595     }
596
597     public static VtepConfigSchema constructVtepConfigSchema(String schemaName, String portName, Integer vlanId,
598                                                              String subnetMask, String gatewayIp, String transportZone,
599                                                              String tunnelType, List<BigInteger> dpnIds,
600                                                              String excludeIpFilter) {
601         IpAddress gatewayIpObj = StringUtils.isBlank(gatewayIp) ? null : IpAddressBuilder.getDefaultInstance(gatewayIp);
602         IpPrefix subnet = StringUtils.isBlank(subnetMask) ? null : IpPrefixBuilder.getDefaultInstance(subnetMask);
603         Class<? extends TunnelTypeBase> tunType ;
604         if (tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN)) {
605             tunType = TunnelTypeVxlan.class ;
606         } else {
607             tunType = TunnelTypeGre.class ;
608         }
609         VtepConfigSchemaBuilder schemaBuilder = new VtepConfigSchemaBuilder().setSchemaName(schemaName)
610                 .setPortName(portName).setVlanId(vlanId).setSubnet(subnet).setGatewayIp(gatewayIpObj)
611                 .setTransportZoneName(transportZone).setTunnelType(tunType).setDpnIds(getDpnIdsListFromBigInt(dpnIds))
612                 .setExcludeIpFilter(excludeIpFilter);
613         return schemaBuilder.build();
614     }
615
616     public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
617         final List<IpAddress> lstIpAddress = new ArrayList<>();
618         if (StringUtils.isBlank(excludeIpFilter)) {
619             return lstIpAddress;
620         }
621         final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
622         for (String ip : arrIps) {
623             if (StringUtils.countMatches(ip, "-") == 1) {
624                 final String[] arrIpRange = StringUtils.split(ip, '-');
625                 String strStartIp = StringUtils.trim(arrIpRange[0]);
626                 String strEndIp = StringUtils.trim(arrIpRange[1]);
627                 Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
628                         "Invalid exclude IP filter: invalid IP address value " + strStartIp);
629                 Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
630                         "Invalid exclude IP filter: invalid IP address value " + strEndIp);
631                 Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
632                         "Invalid exclude IP filter: IP address [" + strStartIp
633                                 + "] not in subnet range " + subnetInfo.getCidrSignature());
634                 Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
635                         "Invalid exclude IP filter: IP address [" + strEndIp
636                                 + "] not in subnet range " + subnetInfo.getCidrSignature());
637                 int startIp = subnetInfo.asInteger(strStartIp);
638                 int endIp = subnetInfo.asInteger(strEndIp);
639
640                 Preconditions.checkArgument(startIp < endIp,
641                         "Invalid exclude IP filter: Invalid range [" + ip + "] ");
642                 for (int iter = startIp; iter <= endIp; iter++) {
643                     String ipAddress = ipFormat(toIpArray(iter));
644                     validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
645                 }
646             } else {
647                 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
648             }
649         }
650         return lstIpAddress;
651     }
652
653     private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
654                                                       String ipAddress) {
655         String ip = StringUtils.trim(ipAddress);
656         Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
657                 "Invalid exclude IP filter: invalid IP address value " + ip);
658         Preconditions.checkArgument(subnetInfo.isInRange(ip),
659                 "Invalid exclude IP filter: IP address [" + ip + "] not in subnet range "
660                         + subnetInfo.getCidrSignature());
661         lstIpAddress.add(IpAddressBuilder.getDefaultInstance(ip));
662     }
663
664     private static int[] toIpArray(int val) {
665         int[] ret = new int[4];
666         for (int iter = 3; iter >= 0; --iter) {
667             ret[iter] |= val >>> 8 * (3 - iter) & 0xff;
668         }
669         return ret;
670     }
671
672     private static String ipFormat(int[] octets) {
673         StringBuilder str = new StringBuilder();
674         for (int iter = 0; iter < octets.length; ++iter) {
675             str.append(octets[iter]);
676             if (iter != octets.length - 1) {
677                 str.append(".");
678             }
679         }
680         return str.toString();
681     }
682
683     public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd,
684                                                                List<BigInteger> lstDpnsForDelete,
685                                                                IITMProvider itmProvider) {
686         Preconditions.checkArgument(StringUtils.isNotBlank(schemaName));
687         if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty())
688                 && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) {
689             Preconditions.checkArgument(false,
690                     "DPN ID list for add | delete is null or empty in schema " + schemaName);
691         }
692         VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName);
693         if (schema == null) {
694             Preconditions.checkArgument(false, "Specified VTEP Schema [" + schemaName
695                     + "] doesn't exists!");
696         }
697         List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds());
698         if (isNotEmpty(lstDpnsForAdd)) {
699             List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds);
700             lstAlreadyExistingDpns.retainAll(lstDpnsForAdd);
701             Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(),
702                     "DPN ID's " + lstAlreadyExistingDpns
703                             + " already exists in VTEP schema [" + schemaName + "]");
704             if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
705                 validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd, itmProvider.getAllVtepConfigSchemas());
706             }
707         }
708         if (isNotEmpty(lstDpnsForDelete)) {
709             if (existingDpnIds.isEmpty()) {
710                 String builder = "DPN ID's " + lstDpnsForDelete
711                         + " specified for delete from VTEP schema [" + schemaName
712                         + "] are not configured in the schema.";
713                 Preconditions.checkArgument(false, builder);
714             } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) {
715                 List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete);
716                 lstConflictingDpns.removeAll(existingDpnIds);
717                 String builder = "DPN ID's " + lstConflictingDpns
718                         + " specified for delete from VTEP schema [" + schemaName
719                         + "] are not configured in the schema.";
720                 Preconditions.checkArgument(false, builder);
721             }
722         }
723         return schema;
724     }
725
726     public static String getSubnetCidrAsString(IpPrefix subnet) {
727         return subnet == null ? StringUtils.EMPTY : String.valueOf(subnet.getValue());
728     }
729
730     public static <T> List<T> emptyIfNull(List<T> list) {
731         return list == null ? Collections.emptyList() : list;
732     }
733
734     public static <T> boolean isEmpty(Collection<T> collection) {
735         return collection == null || collection.isEmpty();
736     }
737
738     public static <T> boolean isNotEmpty(Collection<T> collection) {
739         return !isEmpty(collection);
740     }
741
742     @Nonnull
743     public static HwVtep createHwVtepObject(String topoId, String nodeId, IpAddress ipAddress, IpPrefix ipPrefix,
744                                             IpAddress gatewayIP, int vlanID,
745                                             Class<? extends TunnelTypeBase> tunneltype, TransportZone transportZone) {
746         HwVtep hwVtep = new HwVtep();
747         hwVtep.setGatewayIP(gatewayIP);
748         hwVtep.setHwIp(ipAddress);
749         hwVtep.setIpPrefix(ipPrefix);
750         hwVtep.setNodeId(nodeId);
751         hwVtep.setTopoId(topoId);
752         hwVtep.setTransportZone(transportZone.getZoneName());
753         hwVtep.setTunnelType(tunneltype);
754         hwVtep.setVlanID(vlanID);
755         return hwVtep;
756     }
757
758     public static String getHwParentIf(String topoId, String srcNodeid) {
759         return String.format("%s:%s", topoId, srcNodeid);
760     }
761
762     /**
763      * Synchronous blocking write to data store.
764      *
765      * @deprecated Use
766      * {@link SingleTransactionDataBroker#syncWrite(DataBroker, LogicalDatastoreType, InstanceIdentifier, DataObject)}
767      *             instead of this.
768      */
769     @Deprecated
770     public static <T extends DataObject> void syncWrite(LogicalDatastoreType datastoreType,
771                                                         InstanceIdentifier<T> path, T data, DataBroker broker) {
772         WriteTransaction tx = broker.newWriteOnlyTransaction();
773         tx.put(datastoreType, path, data, true);
774         try {
775             tx.submit().get();
776         } catch (InterruptedException | ExecutionException e) {
777             LOG.error("ITMUtils:SyncWrite , Error writing to datastore (path, data) : ({}, {})", path, data);
778             throw new RuntimeException(e.getMessage(), e);
779         }
780     }
781
782     @Nonnull
783     public static List<BigInteger> getDpnIdList(List<DpnIds> dpnIds) {
784         List<BigInteger> dpnList = new ArrayList<>() ;
785         for (DpnIds dpn : dpnIds) {
786             dpnList.add(dpn.getDPN()) ;
787         }
788         return dpnList ;
789     }
790
791     public static List<DpnIds> getDpnIdsListFromBigInt(List<BigInteger> dpnIds) {
792         List<DpnIds> dpnIdList = new ArrayList<>();
793         DpnIdsBuilder builder = new DpnIdsBuilder();
794         for (BigInteger dpnId : dpnIds) {
795             dpnIdList.add(builder.setKey(new DpnIdsKey(dpnId)).setDPN(dpnId).build());
796         }
797         return dpnIdList;
798     }
799
800     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces
801             .rev140508.interfaces.state.Interface> buildStateInterfaceId(
802             String interfaceName) {
803         return InstanceIdentifier.builder(InterfacesState.class)
804                 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces
805                                .state.Interface.class,
806                        new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces
807                                .rev140508.interfaces.state.InterfaceKey(
808                                interfaceName)).build();
809     }
810
811     @Nonnull
812     public static List<String> getInternalTunnelInterfaces(DataBroker dataBroker) {
813         List<String> tunnelList = new ArrayList<>();
814         Collection<String> internalInterfaces = ITM_CACHE.getAllInternalInterfaces();
815         if (internalInterfaces == null) {
816             updateTunnelsCache(dataBroker);
817             internalInterfaces = ITM_CACHE.getAllInternalInterfaces();
818         }
819         LOG.debug("ItmUtils.getTunnelList Cache Internal Interfaces size: {} ", internalInterfaces.size());
820         tunnelList.addAll(internalInterfaces);
821         LOG.trace("ItmUtils.getTunnelList Internal: {}", tunnelList);
822         return tunnelList;
823     }
824
825     public static List<String> getTunnelsofTzone(List<HwVtep> hwVteps, String tzone, DataBroker dataBroker,
826                                                  Boolean hwVtepsExist) {
827         List<String> tunnels = new ArrayList<>();
828         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class)
829                 .child(TransportZone.class, new TransportZoneKey(tzone)).build();
830         Optional<TransportZone> transportZoneOptional =
831                 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
832         if (transportZoneOptional.isPresent()) {
833             TransportZone transportZone = transportZoneOptional.get();
834             Class<? extends TunnelTypeBase> tunType = transportZone.getTunnelType();
835             if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
836                 for (Subnets sub : transportZone.getSubnets()) {
837                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
838                         for (Vteps vtepLocal : sub.getVteps()) {
839                             for (Vteps vtepRemote : sub.getVteps()) {
840                                 if (!vtepLocal.equals(vtepRemote)) {
841                                     InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(),
842                                             vtepLocal.getDpnId(), tunType);
843                                     InstanceIdentifier<InternalTunnel> intIID =
844                                             InstanceIdentifier.builder(TunnelList.class)
845                                                     .child(InternalTunnel.class, key).build();
846                                     Optional<InternalTunnel> tunnelsOptional =
847                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
848                                     if (tunnelsOptional.isPresent()) {
849                                         List<String> tunnelInterfaceNames = tunnelsOptional
850                                                 .get().getTunnelInterfaceNames();
851                                         if (tunnelInterfaceNames != null && !tunnelInterfaceNames.isEmpty()) {
852                                             String tunnelInterfaceName = tunnelInterfaceNames.get(0);
853                                             LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
854                                             tunnels.add(tunnelInterfaceName);
855                                         }
856                                     }
857                                 }
858                             }
859                             if (hwVteps != null && !hwVteps.isEmpty()) {
860                                 for (HwVtep hwVtep : hwVteps) {
861                                     tunnels.add(getExtTunnel(hwVtep.getNodeId(), vtepLocal.getDpnId().toString(),
862                                             tunType, dataBroker));
863                                     tunnels.add(getExtTunnel(vtepLocal.getDpnId().toString(), hwVtep.getNodeId(),
864                                             tunType, dataBroker));
865                                 }
866                             }
867                         }
868                     }
869                 }
870             }
871             if (hwVtepsExist) {
872                 for (HwVtep hwVtep : hwVteps) {
873                     for (HwVtep hwVtepOther : hwVteps) {
874                         if (!hwVtep.getHwIp().equals(hwVtepOther.getHwIp())) {
875                             tunnels.add(getExtTunnel(hwVtep.getNodeId(), hwVtepOther.getNodeId(),
876                                     tunType, dataBroker));
877                             tunnels.add(getExtTunnel(hwVtepOther.getNodeId(), hwVtep.getNodeId(),
878                                     tunType, dataBroker));
879                         }
880                     }
881                 }
882             }
883         }
884         return tunnels;
885     }
886
887     public static List<String> getInternalTunnelsofTzone(String tzone, DataBroker dataBroker) {
888         List<String> tunnels = new ArrayList<>();
889         LOG.trace("Getting internal tunnels of {}",tzone);
890         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class)
891                 .child(TransportZone.class, new TransportZoneKey(tzone)).build();
892         Optional<TransportZone> transportZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION,
893                 path, dataBroker);
894         if (transportZoneOptional.isPresent()) {
895             TransportZone transportZone = transportZoneOptional.get();
896             if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
897                 for (Subnets sub : transportZone.getSubnets()) {
898                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
899                         for (Vteps vtepLocal : sub.getVteps()) {
900                             for (Vteps vtepRemote : sub.getVteps()) {
901                                 if (!vtepLocal.equals(vtepRemote)) {
902                                     InternalTunnelKey key =
903                                             new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(),
904                                                     transportZone.getTunnelType());
905                                     InstanceIdentifier<InternalTunnel> intIID =
906                                             InstanceIdentifier.builder(TunnelList.class)
907                                                     .child(InternalTunnel.class, key).build();
908                                     Optional<InternalTunnel> tunnelsOptional =
909                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
910                                     if (tunnelsOptional.isPresent()) {
911                                         List<String> tunnelInterfaceNames = tunnelsOptional.get()
912                                                 .getTunnelInterfaceNames();
913                                         if (tunnelInterfaceNames != null && !tunnelInterfaceNames.isEmpty()) {
914                                             String tunnelInterfaceName = tunnelInterfaceNames.get(0);
915                                             LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
916                                             tunnels.add(tunnelInterfaceName);
917                                         }
918                                     }
919                                 }
920                             }
921                         }
922                     }
923                 }
924             }
925         }
926         return tunnels;
927     }
928
929     private static String getExtTunnel(String nodeId, String dpId,Class<? extends TunnelTypeBase> tunType, DataBroker
930             dataBroker) {
931         LOG.trace("getting ext tunnel for {} and dpId {}",nodeId,dpId);
932         ExternalTunnelKey key = getExternalTunnelKey(dpId, nodeId, tunType);
933         InstanceIdentifier<ExternalTunnel> intIID = InstanceIdentifier.builder(ExternalTunnelList.class)
934                 .child(ExternalTunnel.class, key).build();
935         Optional<ExternalTunnel> tunnelsOptional =
936                 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
937         if (tunnelsOptional.isPresent()) {
938             String tunnelInterfaceName = tunnelsOptional.get().getTunnelInterfaceName();
939             LOG.trace("ext tunnel returned {} ", tunnelInterfaceName);
940             return tunnelInterfaceName;
941         }
942         return null;
943     }
944
945     @SuppressFBWarnings("RV_CHECK_FOR_POSITIVE_INDEXOF")
946     public static ExternalTunnelKey getExternalTunnelKey(String dst , String src,
947                                                          Class<? extends TunnelTypeBase> tunType) {
948         final int srcIndex = src.indexOf("physicalswitch");
949         if (srcIndex > 0) {
950             src = src.substring(0, srcIndex - 1);
951         }
952         final int dstIndex = dst.indexOf("physicalswitch");
953         if (dstIndex > 0) {
954             dst = dst.substring(0, dstIndex - 1);
955         }
956         return new ExternalTunnelKey(dst, src, tunType);
957     }
958
959     public static List<TunnelEndPoints> getTEPsForDpn(BigInteger srcDpn, Collection<DPNTEPsInfo> dpnList) {
960         for (DPNTEPsInfo dpn : dpnList) {
961             if (dpn.getDPNID().equals(srcDpn)) {
962                 return dpn.getTunnelEndPoints() ;
963             }
964         }
965         return null;
966     }
967
968     private static List<InternalTunnel> getAllInternalTunnels(DataBroker dataBroker) {
969         List<InternalTunnel> result = null;
970         InstanceIdentifier<TunnelList> iid = InstanceIdentifier.builder(TunnelList.class).build();
971         Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
972         if (tunnelList.isPresent()) {
973             result = tunnelList.get().getInternalTunnel();
974         }
975         if (result == null) {
976             result = Collections.emptyList();
977         }
978         return result;
979     }
980
981     public static InternalTunnel getInternalTunnel(String interfaceName, DataBroker broker) {
982         InternalTunnel internalTunnel = ITM_CACHE.getInternalTunnel(interfaceName);
983         if (internalTunnel == null) {
984             updateTunnelsCache(broker);
985             internalTunnel = ITM_CACHE.getInternalTunnel(interfaceName);
986         }
987         return internalTunnel;
988     }
989
990     public static ExternalTunnel getExternalTunnel(String interfaceName, DataBroker broker) {
991         ExternalTunnel externalTunnel = ITM_CACHE.getExternalTunnel(interfaceName);
992         if (externalTunnel == null) {
993             updateTunnelsCache(broker);
994             externalTunnel = ITM_CACHE.getExternalTunnel(interfaceName);
995         }
996         return externalTunnel;
997     }
998
999     private static List<ExternalTunnel> getAllExternalTunnels(DataBroker dataBroker) {
1000         List<ExternalTunnel> result = null;
1001         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1002         Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1003         if (tunnelList.isPresent()) {
1004             result = tunnelList.get().getExternalTunnel();
1005         }
1006         if (result == null) {
1007             result = Collections.emptyList();
1008         }
1009         return result;
1010     }
1011
1012     public static String convertTunnelTypetoString(Class<? extends TunnelTypeBase> tunType) {
1013         String tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
1014         if (tunType.equals(TunnelTypeVxlan.class)) {
1015             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN ;
1016         } else if (tunType.equals(TunnelTypeGre.class)) {
1017             tunnelType = ITMConstants.TUNNEL_TYPE_GRE ;
1018         } else if (tunType.equals(TunnelTypeMplsOverGre.class)) {
1019             tunnelType = ITMConstants.TUNNEL_TYPE_MPLSoGRE;
1020         } else if (tunType.equals(TunnelTypeLogicalGroup.class)) {
1021             tunnelType = ITMConstants.TUNNEL_TYPE_LOGICAL_GROUP_VXLAN;
1022         }
1023         return tunnelType ;
1024     }
1025
1026
1027     public static boolean isItmIfType(Class<? extends InterfaceType> ifType) {
1028         return ifType != null && ifType.isAssignableFrom(Tunnel.class);
1029     }
1030
1031     public static StateTunnelListKey getTunnelStateKey(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf
1032                                                                .interfaces.rev140508.interfaces.state.Interface iface) {
1033         StateTunnelListKey key = null;
1034         if (isItmIfType(iface.getType())) {
1035             key = new StateTunnelListKey(iface.getName());
1036         }
1037         return key;
1038     }
1039
1040     private static void updateTunnelsCache(DataBroker broker) {
1041         List<InternalTunnel> internalTunnels = getAllInternalTunnels(broker);
1042         for (InternalTunnel tunnel : internalTunnels) {
1043             ITM_CACHE.addInternalTunnel(tunnel);
1044         }
1045         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker);
1046         for (ExternalTunnel tunnel : externalTunnels) {
1047             ITM_CACHE.addExternalTunnel(tunnel);
1048         }
1049     }
1050
1051     public static Interface getInterface(
1052             String name, IInterfaceManager ifaceManager) {
1053         Interface result = ITM_CACHE.getInterface(name);
1054         if (result == null) {
1055             result = ifaceManager.getInterfaceInfoFromConfigDataStore(name);
1056             if (result != null) {
1057                 ITM_CACHE.addInterface(result);
1058             }
1059         }
1060         return result;
1061     }
1062
1063     public static List<DcGatewayIp> getDcGatewayIpList(DataBroker broker) {
1064         InstanceIdentifier<DcGatewayIpList> dcGatewayIpListid =
1065                 InstanceIdentifier.builder(DcGatewayIpList.class).build();
1066         Optional<DcGatewayIpList> dcGatewayIpListConfig =
1067                 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, dcGatewayIpListid, broker);
1068         if (dcGatewayIpListConfig.isPresent()) {
1069             DcGatewayIpList containerList = dcGatewayIpListConfig.get();
1070             if (containerList != null) {
1071                 return containerList.getDcGatewayIp();
1072             }
1073         }
1074         return null;
1075     }
1076
1077     public static boolean falseIfNull(Boolean value) {
1078         return value == null ? false : value;
1079     }
1080
1081     public static <T> List<T> getIntersection(List<T> list1, List<T> list2) {
1082         List<T> list = new ArrayList<>();
1083         for (T iter : list1) {
1084             if (list2.contains(iter)) {
1085                 list.add(iter);
1086             }
1087         }
1088         LOG.debug(" getIntersection - L1 {}, L2 - {}, Intersection - {}", list1, list2, list);
1089         return list;
1090     }
1091
1092     public static void addTransportZoneMembership(List<TzMembership> zones, String zoneName) {
1093         zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());
1094     }
1095
1096     public static  List<TzMembership> createTransportZoneMembership(String zoneName) {
1097         List<TzMembership> zones = new ArrayList<>();
1098         zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());
1099         return zones;
1100     }
1101
1102     /**
1103      * Gets the transport zone in TepsNotHosted list in the Configuration Datastore, based on transport zone name.
1104      *
1105      * @param unknownTz transport zone name
1106      *
1107      * @param dataBroker data broker handle to perform read operations on config datastore
1108      *
1109      * @return the TepsNotHostedInTransportZone object in the TepsNotHosted list in Config DS
1110      */
1111     public static TepsNotHostedInTransportZone getUnknownTransportZoneFromITMConfigDS(
1112         String unknownTz, DataBroker dataBroker) {
1113         InstanceIdentifier<TepsNotHostedInTransportZone> unknownTzPath =
1114             InstanceIdentifier.builder(TransportZones.class)
1115                     .child(TepsNotHostedInTransportZone.class,
1116                     new TepsNotHostedInTransportZoneKey(unknownTz)).build();
1117         Optional<TepsNotHostedInTransportZone> unknownTzOptional =
1118             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, unknownTzPath, dataBroker);
1119         if (unknownTzOptional.isPresent()) {
1120             return unknownTzOptional.get();
1121         }
1122         return null;
1123     }
1124
1125     /**
1126      * Gets the bridge datapath ID from Network topology Node's OvsdbBridgeAugmentation, in the Operational DS.
1127      *
1128      * @param node Network Topology Node
1129      *
1130      * @param bridge bridge name
1131      *
1132      * @param dataBroker data broker handle to perform operations on datastore
1133      *
1134      * @return the datapath ID of bridge in string form
1135      */
1136     public static String getBridgeDpid(Node node, String bridge, DataBroker dataBroker) {
1137         OvsdbBridgeAugmentation ovsdbBridgeAugmentation = null;
1138         Node bridgeNode = null;
1139         String datapathId = null;
1140
1141         NodeId ovsdbNodeId = node.getKey().getNodeId();
1142
1143         NodeId brNodeId = new NodeId(ovsdbNodeId.getValue()
1144             + "/" + ITMConstants.BRIDGE_URI_PREFIX + "/" + bridge);
1145
1146         InstanceIdentifier<Node> bridgeIid =
1147             InstanceIdentifier
1148                 .create(NetworkTopology.class)
1149                 .child(Topology.class, new TopologyKey(IfmConstants.OVSDB_TOPOLOGY_ID))
1150                 .child(Node.class,new NodeKey(brNodeId));
1151
1152         Optional<Node> opBridgeNode = ItmUtils.read(LogicalDatastoreType.OPERATIONAL, bridgeIid, dataBroker);
1153
1154         if (opBridgeNode.isPresent()) {
1155             bridgeNode = opBridgeNode.get();
1156         }
1157         if (bridgeNode != null) {
1158             ovsdbBridgeAugmentation = bridgeNode.getAugmentation(OvsdbBridgeAugmentation.class);
1159         }
1160
1161         if (ovsdbBridgeAugmentation != null && ovsdbBridgeAugmentation.getDatapathId() != null) {
1162             datapathId = ovsdbBridgeAugmentation.getDatapathId().getValue();
1163         }
1164         return datapathId;
1165     }
1166
1167     /**
1168      * Gets the Network topology Node from Operational Datastore
1169      * based on Bridge Augmentation.
1170      *
1171      * @param bridgeAugmentation bridge augmentation of OVSDB node
1172      *
1173      * @param dataBroker data broker handle to perform operations on datastore
1174      *
1175      * @return the Network Topology Node i.e. OVSDB node which is managing the specified bridge
1176      */
1177     public static Node getOvsdbNode(OvsdbBridgeAugmentation bridgeAugmentation,
1178         DataBroker dataBroker) {
1179         Node ovsdbNode = null;
1180         Optional<Node> opOvsdbNode = Optional.absent();
1181         if (bridgeAugmentation != null) {
1182             InstanceIdentifier<Node> ovsdbNodeIid =
1183                 (InstanceIdentifier<Node>) bridgeAugmentation.getManagedBy().getValue();
1184             opOvsdbNode = ItmUtils.read(LogicalDatastoreType.OPERATIONAL, ovsdbNodeIid, dataBroker);
1185         }
1186         if (opOvsdbNode.isPresent()) {
1187             ovsdbNode = opOvsdbNode.get();
1188         }
1189         return ovsdbNode;
1190     }
1191
1192     /**
1193      * Gets the bridge datapath ID in string form from
1194      * Network topology Node's OvsdbBridgeAugmentation in the Operational DS.
1195      *
1196      * @param augmentedNode Ovsdb Augmented Network Topology Node
1197      *
1198      * @return the datapath ID of bridge in string form
1199      */
1200     public static String getStrDatapathId(OvsdbBridgeAugmentation augmentedNode) {
1201         String datapathId = null;
1202         if (augmentedNode != null && augmentedNode.getDatapathId() != null) {
1203             datapathId = augmentedNode.getDatapathId().getValue();
1204         }
1205         return datapathId;
1206     }
1207
1208     /**
1209      * Returns the dummy subnet (255.255.255.255/32) as IpPrefix object.
1210      *
1211      * @return the dummy subnet (255.255.255.255/32) in IpPrefix object
1212      */
1213     public static IpPrefix getDummySubnet() {
1214         return DUMMY_IP_PREFIX;
1215     }
1216
1217     /**
1218      * Deletes the transport zone from Configuration datastore.
1219      *
1220      * @param tzName transport zone name
1221      * @param dataBroker data broker handle to perform operations on datastore
1222      */
1223     public static void deleteTransportZoneFromConfigDS(String tzName, DataBroker dataBroker) {
1224         // check whether transport-zone exists in config DS.
1225         TransportZone transportZoneFromConfigDS = ItmUtils.getTransportZoneFromConfigDS(tzName, dataBroker);
1226         if (transportZoneFromConfigDS != null) {
1227             // it exists, delete default-TZ now
1228             InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class)
1229                     .child(TransportZone.class, new TransportZoneKey(tzName)).build();
1230             LOG.debug("Removing {} transport-zone from config DS.", tzName);
1231             try {
1232                 SingleTransactionDataBroker.syncDelete(dataBroker, LogicalDatastoreType.CONFIGURATION, path);
1233             } catch (TransactionCommitFailedException e) {
1234                 LOG.error("deleteTransportZoneFromConfigDS failed. {} could not be deleted.", tzName, e);
1235             }
1236         }
1237     }
1238
1239     /**
1240      * Validates the tunnelType argument and returnsTunnelTypeBase class object
1241      * corresponding to tunnelType obtained in String format.
1242      *
1243      * @param tunnelType type of tunnel in string form
1244      *
1245      * @return tunnel-type in TunnelTypeBase object
1246      */
1247     public static Class<? extends TunnelTypeBase> getTunnelType(String tunnelType) {
1248         // validate tunnelType string, in case it is NULL or empty, then
1249         // take VXLAN tunnel type by default
1250         if (tunnelType == null || tunnelType.isEmpty()) {
1251             return TUNNEL_TYPE_MAP.get(ITMConstants.TUNNEL_TYPE_VXLAN);
1252         } else if (!tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN)
1253                 && !tunnelType.equals(ITMConstants.TUNNEL_TYPE_GRE)) {
1254             // if tunnel type is some incorrect value, then
1255             // take VXLAN tunnel type by default
1256             return TUNNEL_TYPE_MAP.get(ITMConstants.TUNNEL_TYPE_VXLAN);
1257         }
1258
1259         // return TunnelTypeBase object corresponding to tunnel-type
1260         return TUNNEL_TYPE_MAP.get(tunnelType);
1261     }
1262
1263     public static List<TzMembership> removeTransportZoneMembership(TunnelEndPoints endPts, List<TzMembership> zones) {
1264         LOG.trace(" RemoveTransportZoneMembership TEPs {}, Membership to be removed {} ", endPts, zones);
1265         List<TzMembership> existingTzList = new ArrayList<>(endPts.getTzMembership()) ;
1266         for (TzMembership membership : zones) {
1267             existingTzList.remove(new TzMembershipBuilder().setZoneName(membership.getZoneName()).build());
1268         }
1269         LOG.debug("Modified Membership List {}", existingTzList);
1270         return existingTzList;
1271     }
1272
1273     public static List<TzMembership> getOriginalTzMembership(TunnelEndPoints srcTep, BigInteger dpnId,
1274                                                              Collection<DPNTEPsInfo> meshedDpnList) {
1275         LOG.trace("Original Membership for source DPN {}, source TEP {}", dpnId, srcTep);
1276         for (DPNTEPsInfo dstDpn : meshedDpnList) {
1277             if (dpnId.equals(dstDpn.getDPNID())) {
1278                 List<TunnelEndPoints> endPts = dstDpn.getTunnelEndPoints();
1279                 for (TunnelEndPoints tep : endPts) {
1280                     if (tep.getIpAddress().equals(srcTep.getIpAddress())) {
1281                         LOG.debug("Original Membership size {}", tep.getTzMembership().size()) ;
1282                         return tep.getTzMembership();
1283                     }
1284                 }
1285             }
1286         }
1287         return null ;
1288     }
1289
1290     public static StateTunnelList buildStateTunnelList(StateTunnelListKey tlKey, String name, boolean state,
1291                                                        TunnelOperStatus tunOpStatus, IInterfaceManager  ifaceManager,
1292                                                        DataBroker broker) {
1293         StateTunnelListBuilder stlBuilder = new StateTunnelListBuilder();
1294         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface iface =
1295                 ItmUtils.getInterface(name, ifaceManager);
1296         IfTunnel ifTunnel = iface.getAugmentation(IfTunnel.class);
1297         ParentRefs parentRefs = iface.getAugmentation(ParentRefs.class);
1298         if (ifTunnel == null || parentRefs == null) {
1299             return null;
1300         }
1301         DstInfoBuilder dstInfoBuilder = new DstInfoBuilder();
1302         SrcInfoBuilder srcInfoBuilder = new SrcInfoBuilder();
1303         dstInfoBuilder.setTepIp(ifTunnel.getTunnelDestination());
1304         srcInfoBuilder.setTepIp(ifTunnel.getTunnelSource());
1305         // TODO: Add/Improve logic for device type
1306         InternalTunnel internalTunnel = ItmUtils.ITM_CACHE.getInternalTunnel(name);
1307         ExternalTunnel externalTunnel = ItmUtils.ITM_CACHE.getExternalTunnel(name);
1308         if (internalTunnel == null && externalTunnel == null) {
1309             // both not present in cache. let us update and try again.
1310             ItmUtils.updateTunnelsCache(broker);
1311             internalTunnel = ItmUtils.ITM_CACHE.getInternalTunnel(name);
1312             externalTunnel = ItmUtils.ITM_CACHE.getExternalTunnel(name);
1313         }
1314         if (internalTunnel != null) {
1315             srcInfoBuilder.setTepDeviceId(internalTunnel.getSourceDPN().toString())
1316                     .setTepDeviceType(TepTypeInternal.class);
1317             dstInfoBuilder.setTepDeviceId(internalTunnel.getDestinationDPN().toString())
1318                     .setTepDeviceType(TepTypeInternal.class);
1319             stlBuilder.setTransportType(internalTunnel.getTransportType());
1320         } else if (externalTunnel != null) {
1321             ExternalTunnel tunnel = ItmUtils.ITM_CACHE.getExternalTunnel(name);
1322             srcInfoBuilder.setTepDeviceId(tunnel.getSourceDevice())
1323                     .setTepDeviceType(getDeviceType(tunnel.getSourceDevice()));
1324             dstInfoBuilder.setTepDeviceId(tunnel.getDestinationDevice())
1325                     .setTepDeviceType(getDeviceType(tunnel.getDestinationDevice()))
1326                     .setTepIp(ifTunnel.getTunnelDestination());
1327             stlBuilder.setTransportType(tunnel.getTransportType());
1328         }
1329         stlBuilder.setKey(tlKey).setTunnelInterfaceName(name).setOperState(tunOpStatus).setTunnelState(state)
1330                 .setDstInfo(dstInfoBuilder.build()).setSrcInfo(srcInfoBuilder.build());
1331         return stlBuilder.build();
1332     }
1333
1334     private static Class<? extends TepTypeBase> getDeviceType(String device) {
1335         if (device.startsWith("hwvtep")) {
1336             return TepTypeHwvtep.class;
1337         } else if (device.contains("IpAddress")) {
1338             return TepTypeExternal.class;
1339         } else {
1340             return TepTypeInternal.class;
1341         }
1342     }
1343
1344     public static InstanceIdentifier<StateTunnelList> buildStateTunnelListId(StateTunnelListKey tlKey) {
1345         return InstanceIdentifier.builder(TunnelsState.class)
1346                 .child(StateTunnelList.class, tlKey).build();
1347     }
1348
1349     @Nonnull
1350     public static  Optional<InternalTunnel> getInternalTunnelFromDS(BigInteger srcDpn, BigInteger destDpn,
1351                                                                     Class<? extends TunnelTypeBase> type,
1352                                                                     DataBroker dataBroker) {
1353         InstanceIdentifier<InternalTunnel> pathLogicTunnel = InstanceIdentifier.create(TunnelList.class)
1354                 .child(InternalTunnel.class,
1355                         new InternalTunnelKey(destDpn, srcDpn, type));
1356         //TODO: need to be replaced by cached copy
1357         return ItmUtils.read(LogicalDatastoreType.CONFIGURATION, pathLogicTunnel, dataBroker);
1358     }
1359
1360     public static boolean isTunnelAggregationUsed(Class<? extends TunnelTypeBase> tunType) {
1361         return ItmTunnelAggregationHelper.isTunnelAggregationEnabled()
1362                 && (tunType.isAssignableFrom(TunnelTypeVxlan.class)
1363                 || tunType.isAssignableFrom(TunnelTypeLogicalGroup.class));
1364     }
1365
1366     public static List<TunnelOptions> buildTunnelOptions(TunnelEndPoints tep, ItmConfig itmConfig) {
1367         List<TunnelOptions> tunOptions = new ArrayList<>();
1368
1369         String tos = tep.getOptionTunnelTos();
1370         if (tos == null) {
1371             tos = itmConfig.getDefaultTunnelTos();
1372         }
1373         /* populate tos option only if its not default value of 0 */
1374         if (tos != null && !tos.equals("0")) {
1375             TunnelOptionsBuilder optionsBuilder = new TunnelOptionsBuilder();
1376             optionsBuilder.setKey(new TunnelOptionsKey("tos"));
1377             optionsBuilder.setTunnelOption("tos");
1378             optionsBuilder.setValue(tos);
1379             tunOptions.add(optionsBuilder.build());
1380         }
1381
1382         if (tep.getTunnelType() == TunnelTypeVxlan.class && itmConfig.isGpeExtensionEnabled()) {
1383             TunnelOptionsBuilder optionsBuilder = new TunnelOptionsBuilder();
1384             optionsBuilder.setKey(new TunnelOptionsKey("exts"));
1385             optionsBuilder.setTunnelOption("exts");
1386             optionsBuilder.setValue("gpe");
1387             tunOptions.add(optionsBuilder.build());
1388         }
1389         return tunOptions.isEmpty() ? null : tunOptions;
1390     }
1391
1392     public static ExternalTunnel getExternalTunnelbyExternalTunnelKey(ExternalTunnelKey externalTunnelKey,
1393                                                                       InstanceIdentifier<ExternalTunnel> path,
1394                                                                       DataBroker dataBroker) {
1395         ExternalTunnel exTunnel = ITM_CACHE.getExternalTunnelKeyToExternalTunnels().get(externalTunnelKey);
1396         if (exTunnel == null) {
1397             Optional<ExternalTunnel> ext = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
1398             if (ext.isPresent()) {
1399                 exTunnel = ext.get();
1400             }
1401         }
1402         return exTunnel;
1403     }
1404
1405     public static List<DPNTEPsInfo> getDpnTEPsInfos(DataBroker dataBroker) {
1406         InstanceIdentifier<DpnEndpoints> iid = InstanceIdentifier.builder(DpnEndpoints.class).build();
1407         Optional<DpnEndpoints> dpnEndpoints = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1408         if (dpnEndpoints.isPresent()) {
1409             return dpnEndpoints.get().getDPNTEPsInfo();
1410         } else {
1411             return new ArrayList<>();
1412         }
1413     }
1414
1415     public static InstanceIdentifier<TransportZone> getTZInstanceIdentifier(String tzName) {
1416         return InstanceIdentifier.builder(TransportZones.class).child(TransportZone.class,
1417                 new TransportZoneKey(tzName)).build();
1418     }
1419
1420     /**
1421      * Returns the transport zone from Configuration datastore.
1422      *
1423      * @param tzName transport zone name
1424      * @param dataBroker data broker handle to perform operations on datastore
1425      * @return the TransportZone object in Config DS
1426      */
1427     // FIXME: Better is to implement cache to avoid datastore read.
1428     public static TransportZone getTransportZoneFromConfigDS(String tzName, DataBroker dataBroker) {
1429         InstanceIdentifier<TransportZone> tzonePath = getTZInstanceIdentifier(tzName);
1430         Optional<TransportZone> transportZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, tzonePath,
1431                 dataBroker);
1432         if (transportZoneOptional.isPresent()) {
1433             return transportZoneOptional.get();
1434         }
1435         return null;
1436     }
1437
1438     public static Class<? extends TunnelTypeBase> convertStringToTunnelType(String tunnelType) {
1439         Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
1440         if (STRING_CLASS_IMMUTABLE_BI_MAP.containsKey(tunnelType)) {
1441             tunType = STRING_CLASS_IMMUTABLE_BI_MAP.get(tunnelType);
1442         }
1443         return tunType ;
1444     }
1445 }