ITM: Implementation of BFD monitoring
[genius.git] / itm / itm-impl / src / main / java / org / opendaylight / genius / itm / impl / ItmUtils.java
1 /*
2  * Copyright (c) 2016 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.net.InetAddresses;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import org.apache.commons.lang3.StringUtils;
17 import org.apache.commons.net.util.SubnetUtils;
18 import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
19 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
20 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
21 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
22 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
23 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
24 import org.opendaylight.genius.itm.api.IITMProvider;
25 import org.opendaylight.genius.itm.confighelpers.HwVtep;
26 import org.opendaylight.genius.itm.globals.ITMConstants;
27 import org.opendaylight.genius.mdsalutil.*;
28 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.Tunnel;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorParams;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.StateTunnelListKey;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.*;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.*;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeGre;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifier;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierKey;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorInterval;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.VtepConfigSchemas;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.VtepIpPools;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchema;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIds;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsKey;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPool;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPoolKey;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpoints;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpointsBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelList;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfo;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoKey;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPoints;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsKey;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnel;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelBuilder;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelKey;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.TransportZones;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZone;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZoneKey;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.Subnets;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.subnets.Vteps;
79 import org.opendaylight.yangtools.yang.binding.DataObject;
80 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
81 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
82 import org.opendaylight.yangtools.yang.common.RpcResult;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85
86 import java.math.BigInteger;
87 import java.net.InetAddress;
88 import java.util.ArrayList;
89 import java.util.Collection;
90 import java.util.Collections;
91 import java.util.List;
92 import java.util.concurrent.ExecutionException;
93 import java.util.concurrent.Future;
94
95 public class ItmUtils {
96
97     public static final String DUMMY_IP_ADDRESS = "0.0.0.0";
98     public static final String TUNNEL_TYPE_VXLAN = "VXLAN";
99     public static final String TUNNEL_TYPE_GRE = "GRE";
100     public static final String TUNNEL = "TUNNEL";
101     public static ItmCache itmCache = new ItmCache();
102
103     private static final Logger LOG = LoggerFactory.getLogger(ItmUtils.class);
104
105     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
106         public void onSuccess(Void result) {
107             LOG.debug("Success in Datastore write operation");
108         }
109
110         public void onFailure(Throwable error) {
111             LOG.error("Error in Datastore write operation", error);
112         }
113     };
114
115     public static <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
116                                                           InstanceIdentifier<T> path, DataBroker broker) {
117
118         ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
119
120         Optional<T> result = Optional.absent();
121         try {
122             result = tx.read(datastoreType, path).get();
123         } catch (Exception e) {
124             throw new RuntimeException(e);
125         }
126
127         return result;
128     }
129
130     public static <T extends DataObject> void asyncWrite(LogicalDatastoreType datastoreType,
131                                                          InstanceIdentifier<T> path, T data, DataBroker broker, FutureCallback<Void> callback) {
132         WriteTransaction tx = broker.newWriteOnlyTransaction();
133         tx.put(datastoreType, path, data, true);
134         Futures.addCallback(tx.submit(), callback);
135     }
136
137     public static <T extends DataObject> void asyncUpdate(LogicalDatastoreType datastoreType,
138                                                           InstanceIdentifier<T> path, T data, DataBroker broker, FutureCallback<Void> callback) {
139         WriteTransaction tx = broker.newWriteOnlyTransaction();
140         tx.merge(datastoreType, path, data, true);
141         Futures.addCallback(tx.submit(), callback);
142     }
143
144     public static <T extends DataObject> void asyncDelete(LogicalDatastoreType datastoreType,
145                                                           InstanceIdentifier<T> path, DataBroker broker, FutureCallback<Void> callback) {
146         WriteTransaction tx = broker.newWriteOnlyTransaction();
147         tx.delete(datastoreType, path);
148         Futures.addCallback(tx.submit(), callback);
149     }
150     public static <T extends DataObject> void asyncBulkRemove(final DataBroker broker,final LogicalDatastoreType datastoreType,
151                                                               List<InstanceIdentifier<T>> pathList, FutureCallback<Void> callback) {
152         if (!pathList.isEmpty()) {
153             WriteTransaction tx = broker.newWriteOnlyTransaction();
154             for (InstanceIdentifier<T> path : pathList) {
155                 tx.delete(datastoreType, path);
156             }
157             Futures.addCallback(tx.submit(), callback);
158         }
159     }
160
161     public static String getInterfaceName(final BigInteger datapathid, final String portName, final Integer vlanId) {
162         return String.format("%s:%s:%s", datapathid, portName, vlanId);
163     }
164
165     public static BigInteger getDpnIdFromInterfaceName(String interfaceName) {
166         String[] dpnStr = interfaceName.split(":");
167         BigInteger dpnId = new BigInteger(dpnStr[0]);
168         return dpnId;
169     }
170
171     public static String getTrunkInterfaceName(IdManagerService idManager, String parentInterfaceName,
172                                                String localHostName, String remoteHostName, String tunnelType) {
173         String tunnelTypeStr;
174         if(tunnelType.contains("TunnelTypeGre")) {
175             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_GRE;
176         } else {
177             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_VXLAN;
178         }
179         String trunkInterfaceName = String.format(  "%s:%s:%s:%s", parentInterfaceName, localHostName,
180                 remoteHostName, tunnelTypeStr);
181         LOG.trace("trunk interface name is {}", trunkInterfaceName);
182         trunkInterfaceName = String.format("%s:%s", TUNNEL, getUniqueId(idManager, trunkInterfaceName));
183         return trunkInterfaceName;
184     }
185
186     public static void releaseIdForTrunkInterfaceName(IdManagerService idManager, String parentInterfaceName, String localHostName, String remoteHostName, String tunnelType) {
187         String tunnelTypeStr;
188         if(tunnelType.contains("TunnelTypeGre")) {
189             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_GRE;
190         } else {
191             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_VXLAN;
192         }
193         String trunkInterfaceName = String.format("%s:%s:%s:%s", parentInterfaceName, localHostName, remoteHostName, tunnelTypeStr);
194         LOG.trace("Releasing Id for trunkInterface - {}", trunkInterfaceName );
195         releaseId(idManager, trunkInterfaceName) ;
196     }
197
198     public static InetAddress getInetAddressFromIpAddress(IpAddress ip) {
199         return InetAddresses.forString(ip.getIpv4Address().getValue());
200     }
201
202     public static InstanceIdentifier<DPNTEPsInfo> getDPNTEPInstance(BigInteger dpIdKey) {
203         InstanceIdentifier.InstanceIdentifierBuilder<DPNTEPsInfo> dpnTepInfoBuilder =
204                 InstanceIdentifier.builder(DpnEndpoints.class).child(DPNTEPsInfo.class,
205                         new DPNTEPsInfoKey(dpIdKey));
206         InstanceIdentifier<DPNTEPsInfo> dpnInfo = dpnTepInfoBuilder.build();
207         return dpnInfo;
208     }
209
210     public static DPNTEPsInfo createDPNTepInfo(BigInteger dpId, List<TunnelEndPoints> endpoints) {
211
212         return new DPNTEPsInfoBuilder().setKey(new DPNTEPsInfoKey(dpId)).setTunnelEndPoints(endpoints).build();
213     }
214
215     public static TunnelEndPoints createTunnelEndPoints(BigInteger dpnId, IpAddress ipAddress, String portName, int vlanId,
216                                                         IpPrefix prefix, IpAddress gwAddress, String zoneName, Class<? extends TunnelTypeBase>  tunnel_type) {
217         // when Interface Mgr provides support to take in Dpn Id
218         return new TunnelEndPointsBuilder().setKey(new TunnelEndPointsKey(ipAddress, portName,tunnel_type, vlanId))
219                 .setSubnetMask(prefix).setGwIpAddress(gwAddress).setTransportZone(zoneName)
220                 .setInterfaceName(ItmUtils.getInterfaceName(dpnId, portName, vlanId)).setTunnelType(tunnel_type).build();
221     }
222
223     public static DpnEndpoints createDpnEndpoints(List<DPNTEPsInfo> dpnTepInfo) {
224         return new DpnEndpointsBuilder().setDPNTEPsInfo(dpnTepInfo).build();
225     }
226
227     public static InstanceIdentifier<Interface> buildId(String interfaceName) {
228         InstanceIdentifierBuilder<Interface> idBuilder =
229                 InstanceIdentifier.builder(Interfaces.class).child(Interface.class, new InterfaceKey(interfaceName));
230         InstanceIdentifier<Interface> id = idBuilder.build();
231         return id;
232     }
233
234     public static Interface buildTunnelInterface(BigInteger dpn, String ifName, String desc, boolean enabled, Class<? extends TunnelTypeBase> tunType,
235                                                  IpAddress localIp, IpAddress remoteIp, IpAddress gatewayIp,Integer vlanId, boolean internal, Boolean monitorEnabled, Class<? extends TunnelMonitoringTypeBase> monitorProtocol, Integer monitorInterval) {
236         InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(ifName)).setName(ifName)
237                 .setDescription(desc).setEnabled(enabled).setType(Tunnel.class);
238         ParentRefs parentRefs = new ParentRefsBuilder().setDatapathNodeIdentifier(dpn).build();
239         builder.addAugmentation(ParentRefs.class, parentRefs);
240         if( vlanId > 0) {
241             IfL2vlan l2vlan = new IfL2vlanBuilder().setVlanId(new VlanId(vlanId)).build();
242             builder.addAugmentation(IfL2vlan.class, l2vlan);
243         }
244         LOG.debug("buildTunnelInterface: monitorProtocol = {} and monitorInterval = {}",monitorProtocol.getName(),monitorInterval);
245
246         Long monitoringInterval = (long)ITMConstants.BFD_DEFAULT_MONITOR_INTERVAL;
247         Boolean monitoringEnabled = true;
248         if(monitorInterval!= null)
249             monitoringInterval = monitorInterval.longValue();
250         else {
251             if (monitorProtocol.getName().contains("Bfd"))
252                 monitoringInterval = (long) ITMConstants.BFD_DEFAULT_MONITOR_INTERVAL;
253             else
254                 monitoringInterval = (long) ITMConstants.DEFAULT_MONITOR_INTERVAL;
255         }
256         LOG.debug("buildTunnelInterface: monitorProtocol = {} and monitorInterval = {}",monitorProtocol.getName(),monitorInterval);
257
258         if(monitorEnabled!=null  )
259             monitoringEnabled = monitorEnabled;
260         IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(remoteIp).setTunnelGateway(
261                 gatewayIp).setTunnelSource(localIp)
262                 .setTunnelInterfaceType(tunType).setInternal(internal).setMonitorEnabled(
263                         monitoringEnabled).setMonitorProtocol(monitorProtocol).setMonitorInterval(monitoringInterval).build();
264         builder.addAugmentation(IfTunnel.class, tunnel);
265         return builder.build();
266     }
267
268     public static Interface buildHwTunnelInterface(String tunnelIfName, String desc, boolean enabled, String topo_id,
269                                                    String node_id, Class<? extends TunnelTypeBase> tunType, IpAddress srcIp, IpAddress destIp,
270                                                    IpAddress gWIp, Boolean monitor_enabled, Class<? extends TunnelMonitoringTypeBase> monitorProtocol, Integer monitor_interval){
271         InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(tunnelIfName)).setName(
272                 tunnelIfName).setDescription(desc).
273                 setEnabled(enabled).setType(Tunnel.class);
274         List<NodeIdentifier> nodeIds = new ArrayList<NodeIdentifier>();
275         NodeIdentifier hWnode = new NodeIdentifierBuilder().setKey(new NodeIdentifierKey(topo_id)).setTopologyId(
276                 topo_id).
277                 setNodeId(node_id).build();
278         nodeIds.add(hWnode);
279         ParentRefs parent = new ParentRefsBuilder().setNodeIdentifier(nodeIds).build();
280         builder.addAugmentation(ParentRefs.class, parent);
281         Long monitoringInterval = (long) ITMConstants.DEFAULT_MONITOR_INTERVAL;
282         Boolean monitoringEnabled = true;
283         Class<? extends TunnelMonitoringTypeBase> monitoringProtocol = ITMConstants.DEFAULT_MONITOR_PROTOCOL;
284         if(monitor_interval!= null)
285             monitoringInterval = monitor_interval.longValue();
286         if(monitor_enabled!=null  )
287             monitoringEnabled = monitor_enabled;
288         if(monitorProtocol!=null)
289             monitoringProtocol = monitorProtocol;
290         IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(destIp).setTunnelGateway(gWIp).setTunnelSource(
291                 srcIp).setMonitorEnabled(monitoringEnabled).setMonitorProtocol(monitorProtocol).setMonitorInterval(100L).
292                 setTunnelInterfaceType(tunType).setInternal(false).build();
293         builder.addAugmentation(IfTunnel.class, tunnel);
294         LOG.trace("iftunnel {} built from hwvtep {} ", tunnel, node_id);
295         return builder.build();
296     }
297
298
299     public static InternalTunnel buildInternalTunnel( BigInteger srcDpnId, BigInteger dstDpnId,
300                                                       Class<? extends TunnelTypeBase> tunType,
301                                                       String trunkInterfaceName) {
302         InternalTunnel tnl = new InternalTunnelBuilder().setKey(new InternalTunnelKey(dstDpnId, srcDpnId, tunType)).setDestinationDPN(dstDpnId)
303                 .setSourceDPN(srcDpnId).setTransportType(tunType)
304                 .setTunnelInterfaceName(trunkInterfaceName).build();
305         return tnl ;
306     }
307
308     public static ExternalTunnel buildExternalTunnel(String srcNode, String dstNode,
309                                                      Class<? extends TunnelTypeBase> tunType,
310                                                      String trunkInterfaceName) {
311         ExternalTunnel extTnl = new ExternalTunnelBuilder().setKey(
312                 new ExternalTunnelKey(dstNode, srcNode, tunType))
313                 .setSourceDevice(srcNode).setDestinationDevice(dstNode)
314                 .setTunnelInterfaceName(trunkInterfaceName)
315                 .setTransportType(tunType).build();
316         return extTnl ;
317     }
318
319     public static List<DPNTEPsInfo> getTunnelMeshInfo(DataBroker dataBroker) {
320         List<DPNTEPsInfo> dpnTEPs= null ;
321
322         // Read the EndPoint Info from the operational database
323         InstanceIdentifierBuilder<DpnEndpoints> depBuilder = InstanceIdentifier.builder( DpnEndpoints.class);
324         InstanceIdentifier<DpnEndpoints> deps = depBuilder.build();
325         Optional<DpnEndpoints> dpnEps = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, deps, dataBroker);
326         if (dpnEps.isPresent()) {
327             DpnEndpoints tn= dpnEps.get() ;
328             dpnTEPs = tn.getDPNTEPsInfo();
329             LOG.debug( "Read from CONFIGURATION datastore - No. of Dpns " , dpnTEPs.size() );
330         }else
331             LOG.debug( "No Dpn information in CONFIGURATION datastore "  );
332         return dpnTEPs ;
333     }
334
335     public static int getUniqueId(IdManagerService idManager, String idKey) {
336         AllocateIdInput getIdInput = new AllocateIdInputBuilder()
337                 .setPoolName(ITMConstants.ITM_IDPOOL_NAME)
338                 .setIdKey(idKey).build();
339
340         try {
341             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
342             RpcResult<AllocateIdOutput> rpcResult = result.get();
343             if(rpcResult.isSuccessful()) {
344                 return rpcResult.getResult().getIdValue().intValue();
345             } else {
346                 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
347             }
348         } catch (InterruptedException | ExecutionException e) {
349             LOG.warn("Exception when getting Unique Id",e);
350         }
351         return 0;
352     }
353
354     public static void releaseId(IdManagerService idManager, String idKey) {
355         ReleaseIdInput idInput =
356                 new ReleaseIdInputBuilder().setPoolName(ITMConstants.ITM_IDPOOL_NAME).setIdKey(idKey).build();
357         try {
358             Future<RpcResult<Void>> result = idManager.releaseId(idInput);
359             RpcResult<Void> rpcResult = result.get();
360             if(!rpcResult.isSuccessful()) {
361                 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
362             }
363         } catch (InterruptedException | ExecutionException e) {
364             LOG.warn("Exception when getting Unique Id for key {}", idKey, e);
365         }
366     }
367
368     public static List<DPNTEPsInfo> getDPNTEPListFromDPNId(DataBroker dataBroker, List<BigInteger> dpnIds) {
369         List<DPNTEPsInfo> meshedDpnList = getTunnelMeshInfo(dataBroker) ;
370         List<DPNTEPsInfo> cfgDpnList = new ArrayList<DPNTEPsInfo>();
371         if( null != meshedDpnList) {
372             for(BigInteger dpnId : dpnIds) {
373                 for( DPNTEPsInfo teps : meshedDpnList ) {
374                     if( dpnId.equals(teps.getDPNID()))
375                         cfgDpnList.add( teps) ;
376                 }
377             }
378         }
379         return cfgDpnList;
380     }
381
382     public static void setUpOrRemoveTerminatingServiceTable(BigInteger dpnId, IMdsalApiManager mdsalManager, boolean addFlag) {
383         String logmsg = ( addFlag == true) ? "Installing" : "Removing";
384         LOG.trace( logmsg + " PUNT to Controller flow in DPN {} ", dpnId );
385         long dpId;
386         List<ActionInfo> listActionInfo = new ArrayList<ActionInfo>();
387         listActionInfo.add(new ActionInfo(ActionType.punt_to_controller,
388                 new String[] {}));
389
390         try {
391             List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
392
393             mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {
394                     BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID) }));
395
396             List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>();
397             mkInstructions.add(new InstructionInfo(InstructionType.apply_actions,
398                     listActionInfo));
399
400             FlowEntity terminatingServiceTableFlowEntity = MDSALUtil
401                     .buildFlowEntity(
402                             dpnId,
403                             NwConstants.INTERNAL_TUNNEL_TABLE,
404                             getFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE,
405                                     ITMConstants.LLDP_SERVICE_ID), 5, String.format("%s:%d","ITM Flow Entry ",ITMConstants.LLDP_SERVICE_ID),
406                             0, 0, ITMConstants.COOKIE_ITM
407                                     .add(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)),
408                             mkMatches, mkInstructions);
409             if(addFlag)
410                 mdsalManager.installFlow(terminatingServiceTableFlowEntity);
411             else
412                 mdsalManager.removeFlow(terminatingServiceTableFlowEntity);
413         } catch (Exception e) {
414             LOG.error("Error while setting up Table 36 for {}", dpnId, e);
415         }
416     }
417
418     private static String getFlowRef(long termSvcTable, int svcId) {
419         return new StringBuffer().append(termSvcTable).append(svcId).toString();
420     }
421     public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier(String schemaName) {
422         return InstanceIdentifier.builder(VtepConfigSchemas.class)
423                 .child(VtepConfigSchema.class, new VtepConfigSchemaKey(schemaName)).build();
424     }
425
426     public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier() {
427         return InstanceIdentifier.builder(VtepConfigSchemas.class).child(VtepConfigSchema.class).build();
428     }
429     public static InstanceIdentifier<VtepConfigSchemas> getVtepConfigSchemasIdentifier() {
430         return InstanceIdentifier.builder(VtepConfigSchemas.class).build();
431     }
432     public static InstanceIdentifier<VtepIpPool> getVtepIpPoolIdentifier(String subnetCidr) {
433         return InstanceIdentifier.builder(VtepIpPools.class).child(VtepIpPool.class, new VtepIpPoolKey(subnetCidr))
434                 .build();
435     }
436     public static VtepConfigSchema validateForAddVtepConfigSchema(VtepConfigSchema schema,
437                                                                   List<VtepConfigSchema> existingSchemas) {
438         VtepConfigSchema validSchema = validateVtepConfigSchema(schema);
439         for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
440             if (!StringUtils.equalsIgnoreCase(schema.getSchemaName(), existingSchema.getSchemaName())
441                     && schema.getSubnet().equals(existingSchema.getSubnet())) {
442                 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
443                 Preconditions.checkArgument(false, new StringBuilder("VTEP schema with subnet [").append(subnetCidr)
444                         .append("] already exists. Multiple VTEP schemas with same subnet is not allowed.").toString());
445             }
446         }
447         if (isNotEmpty(getDpnIdList(validSchema.getDpnIds()))) {
448             String tzone = validSchema.getTransportZoneName();
449             List<BigInteger> lstDpns = getConflictingDpnsAlreadyConfiguredWithTz(validSchema.getSchemaName(), tzone,
450                     getDpnIdList(validSchema.getDpnIds()), existingSchemas);
451             if (!lstDpns.isEmpty()) {
452                 Preconditions.checkArgument(false,
453                         new StringBuilder("DPN's ").append(lstDpns).append(" already configured for transport zone ")
454                                 .append(tzone).append(". Only one end point per transport Zone per Dpn is allowed.")
455                                 .toString());
456             }
457             if (schema.getTunnelType().equals(TunnelTypeGre.class)){
458                 validateForSingleGreTep(validSchema.getSchemaName(), getDpnIdList(validSchema.getDpnIds()), existingSchemas);
459             }
460         }
461         return validSchema;
462     }
463     private static void validateForSingleGreTep(String schemaName, List<BigInteger> lstDpnsForAdd,
464                                                 List<VtepConfigSchema> existingSchemas) {
465         for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
466             if ((TunnelTypeGre.class).equals(existingSchema.getTunnelType())
467                     && !StringUtils.equalsIgnoreCase(schemaName, existingSchema.getSchemaName())) {
468                 List<BigInteger> lstConflictingDpns = new ArrayList<>(getDpnIdList(existingSchema.getDpnIds()));
469                 lstConflictingDpns.retainAll(emptyIfNull(lstDpnsForAdd));
470                 if (!lstConflictingDpns.isEmpty()) {
471                     String errMsg = new StringBuilder("DPN's ").append(lstConflictingDpns)
472                             .append(" already configured with GRE TEP. Mutiple GRE TEP's on a single DPN are not allowed.")
473                             .toString();
474                     Preconditions.checkArgument(false, errMsg);
475                 }
476             }
477         }
478     }
479     public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
480         Preconditions.checkNotNull(schema);
481         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
482         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
483         Preconditions.checkArgument((schema.getVlanId() >= 0 && schema.getVlanId() < 4095),
484                 "Invalid VLAN ID, range (0-4094)");
485         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
486         Preconditions.checkNotNull(schema.getSubnet());
487         String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
488         SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
489         IpAddress gatewayIp = schema.getGatewayIp();
490         if (gatewayIp != null) {
491             String strGatewayIp = String.valueOf(gatewayIp.getValue());
492             if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS) && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
493                 Preconditions.checkArgument(false, new StringBuilder("Gateway IP address ").append(strGatewayIp)
494                         .append(" is not in subnet range ").append(subnetCidr).toString());
495             }
496         }
497         ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
498         return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
499     }
500     public static String validateTunnelType(String tunnelType) {
501         if (tunnelType == null) {
502             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
503         } else {
504             tunnelType = StringUtils.upperCase(tunnelType);
505             String error = new StringBuilder("Invalid tunnel type. Valid values: ")
506                     .append(ITMConstants.TUNNEL_TYPE_VXLAN).append(" | ").append(ITMConstants.TUNNEL_TYPE_GRE)
507                     .toString();
508             Preconditions.checkArgument(ITMConstants.TUNNEL_TYPE_VXLAN.equals(tunnelType)
509                     || ITMConstants.TUNNEL_TYPE_GRE.equals(tunnelType), error);
510         }
511         return tunnelType;
512     }
513     private static List<BigInteger> getConflictingDpnsAlreadyConfiguredWithTz(String schemaName, String tzone,
514                                                                               List<BigInteger> lstDpns, List<VtepConfigSchema> existingSchemas) {
515         List<BigInteger> lstConflictingDpns = new ArrayList<>();
516         for (VtepConfigSchema schema : emptyIfNull(existingSchemas)) {
517             if (!StringUtils.equalsIgnoreCase(schemaName, schema.getSchemaName())
518                     && StringUtils.equals(schema.getTransportZoneName(), tzone)) {
519                 lstConflictingDpns = new ArrayList<>(getDpnIdList(schema.getDpnIds()));
520                 lstConflictingDpns.retainAll(lstDpns);
521                 if (!lstConflictingDpns.isEmpty()) {
522                     break;
523                 }
524             }
525         }
526         return lstConflictingDpns;
527     }
528     public static VtepConfigSchema constructVtepConfigSchema(String schemaName, String portName, Integer vlanId,
529                                                              String subnetMask, String gatewayIp, String transportZone,String tunnelType, List<BigInteger> dpnIds,
530                                                              String excludeIpFilter) {
531         IpAddress gatewayIpObj = StringUtils.isBlank(gatewayIp) ? null : new IpAddress(gatewayIp.toCharArray());
532         IpPrefix subnet = StringUtils.isBlank(subnetMask) ? null : new IpPrefix(subnetMask.toCharArray());
533         Class<? extends TunnelTypeBase> tunType ;
534         if( tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN))
535             tunType = TunnelTypeVxlan.class ;
536         else
537             tunType = TunnelTypeGre.class ;
538         VtepConfigSchemaBuilder schemaBuilder = new VtepConfigSchemaBuilder().setSchemaName(schemaName)
539                 .setPortName(portName).setVlanId(vlanId).setSubnet(subnet).setGatewayIp(gatewayIpObj)
540                 .setTransportZoneName(transportZone).setTunnelType(tunType).setDpnIds(getDpnIdsListFromBigInt(dpnIds))
541                 .setExcludeIpFilter(excludeIpFilter);
542         return schemaBuilder.build();
543     }
544     public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
545         final List<IpAddress> lstIpAddress = new ArrayList<>();
546         if (StringUtils.isBlank(excludeIpFilter)) {
547             return lstIpAddress;
548         }
549         final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
550         for (String ip : arrIps) {
551             if (StringUtils.countMatches(ip, "-") == 1) {
552                 final String[] arrIpRange = StringUtils.split(ip, '-');
553                 String strStartIp = StringUtils.trim(arrIpRange[0]);
554                 String strEndIp = StringUtils.trim(arrIpRange[1]);
555                 Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
556                         new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strStartIp)
557                                 .toString());
558                 Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
559                         new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strEndIp)
560                                 .toString());
561                 Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
562                         new StringBuilder("Invalid exclude IP filter: IP address [").append(strStartIp)
563                                 .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
564                 Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
565                         new StringBuilder("Invalid exclude IP filter: IP address [").append(strEndIp)
566                                 .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
567                 int startIp = subnetInfo.asInteger(strStartIp);
568                 int endIp = subnetInfo.asInteger(strEndIp);
569
570                 Preconditions.checkArgument(startIp < endIp,
571                         new StringBuilder("Invalid exclude IP filter: Invalid range [").append(ip).append("] ")
572                                 .toString());
573                 for (int i = startIp; i <= endIp; i++) {
574                     String ipAddress = ipFormat(toIpArray(i));
575                     validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
576                 }
577             } else {
578                 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
579             }
580         }
581         return lstIpAddress;
582     }
583     private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
584                                                       String ipAddress) {
585         String ip = StringUtils.trim(ipAddress);
586         Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
587                 new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(ip).toString());
588         Preconditions.checkArgument(subnetInfo.isInRange(ip),
589                 new StringBuilder("Invalid exclude IP filter: IP address [").append(ip).append("] not in subnet range ")
590                         .append(subnetInfo.getCidrSignature()).toString());
591         lstIpAddress.add(new IpAddress(ip.toCharArray()));
592     }
593     private static int[] toIpArray(int val) {
594         int[] ret = new int[4];
595         for (int j = 3; j >= 0; --j) {
596             ret[j] |= ((val >>> 8 * (3 - j)) & (0xff));
597         }
598         return ret;
599     }
600     private static String ipFormat(int[] octets) {
601         StringBuilder str = new StringBuilder();
602         for (int i = 0; i < octets.length; ++i) {
603             str.append(octets[i]);
604             if (i != octets.length - 1) {
605                 str.append(".");
606             }
607         }
608         return str.toString();
609     }
610     public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd,
611                                                                List<BigInteger> lstDpnsForDelete, IITMProvider itmProvider) {
612         Preconditions.checkArgument(StringUtils.isNotBlank(schemaName));
613         if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty())
614                 && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) {
615             Preconditions.checkArgument(false,
616                     new StringBuilder("DPN ID list for add | delete is null or empty in schema ").append(schemaName)
617                             .toString());
618         }
619         VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName);
620         if (schema == null) {
621             Preconditions.checkArgument(false, new StringBuilder("Specified VTEP Schema [").append(schemaName)
622                     .append("] doesn't exists!").toString());
623         }
624         List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds());
625         if (isNotEmpty(lstDpnsForAdd)) {
626             //  if (isNotEmpty(existingDpnIds)) {
627             List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds);
628             lstAlreadyExistingDpns.retainAll(lstDpnsForAdd);
629             Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(),
630                     new StringBuilder("DPN ID's ").append(lstAlreadyExistingDpns)
631                             .append(" already exists in VTEP schema [").append(schemaName).append("]").toString());
632             //    }
633             if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
634                 validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd, itmProvider.getAllVtepConfigSchemas());
635             }
636         }
637         if (isNotEmpty(lstDpnsForDelete)) {
638             if (existingDpnIds == null || existingDpnIds.isEmpty()) {
639                 StringBuilder builder = new StringBuilder("DPN ID's ").append(lstDpnsForDelete)
640                         .append(" specified for delete from VTEP schema [").append(schemaName)
641                         .append("] are not configured in the schema.");
642                 Preconditions.checkArgument(false, builder.toString());
643             } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) {
644                 List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete);
645                 lstConflictingDpns.removeAll(existingDpnIds);
646                 StringBuilder builder = new StringBuilder("DPN ID's ").append(lstConflictingDpns)
647                         .append(" specified for delete from VTEP schema [").append(schemaName)
648                         .append("] are not configured in the schema.");
649                 Preconditions.checkArgument(false, builder.toString());
650             }
651         }
652         return schema;
653     }
654     public static String getSubnetCidrAsString(IpPrefix subnet) {
655         return (subnet == null) ? StringUtils.EMPTY : String.valueOf(subnet.getValue());
656     }
657     public static <T> List<T> emptyIfNull(List<T> list) {
658         return (list == null) ? Collections.<T> emptyList() : list;
659     }
660     public static <T> boolean isEmpty(Collection<T> collection) {
661         return (collection == null || collection.isEmpty()) ? true : false;
662     }
663     public static <T> boolean isNotEmpty(Collection<T> collection) {
664         return !isEmpty(collection);
665     }
666     public static HwVtep createHwVtepObject(String topo_id, String node_id, IpAddress ipAddress, IpPrefix ipPrefix, IpAddress gatewayIP, int vlanID, Class<? extends TunnelTypeBase> tunnel_type, TransportZone transportZone) {
667         HwVtep hwVtep = new HwVtep();
668         hwVtep.setGatewayIP(gatewayIP);
669         hwVtep.setHwIp(ipAddress);
670         hwVtep.setIpPrefix(ipPrefix);
671         hwVtep.setNode_id(node_id);
672         hwVtep.setTopo_id(topo_id);
673         hwVtep.setTransportZone(transportZone.getZoneName());
674         hwVtep.setTunnel_type(tunnel_type);
675         hwVtep.setVlanID(vlanID);
676         return hwVtep;
677     }
678
679     public static String getHwParentIf(String topo_id, String srcNodeid) {
680         return String.format("%s:%s", topo_id, srcNodeid);
681     }
682
683     public static <T extends DataObject> void syncWrite(LogicalDatastoreType datastoreType,
684                                                         InstanceIdentifier<T> path, T data, DataBroker broker) {
685         WriteTransaction tx = broker.newWriteOnlyTransaction();
686         tx.put(datastoreType, path, data, true);
687         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
688         try {
689             futures.get();
690         } catch (InterruptedException | ExecutionException e) {
691             LOG.error("ITMUtils:SyncWrite , Error writing to datastore (path, data) : ({}, {})", path, data);
692             throw new RuntimeException(e.getMessage());
693         }
694     }
695
696     public static List<BigInteger> getDpnIdList( List<DpnIds> dpnIds ) {
697         List<BigInteger> dpnList = new ArrayList<BigInteger>() ;
698         for( DpnIds dpn : dpnIds) {
699             dpnList.add(dpn.getDPN()) ;
700         }
701         return dpnList ;
702     }
703
704     public static List<DpnIds> getDpnIdsListFromBigInt( List<BigInteger> dpnIds) {
705         List<DpnIds> dpnIdList = new ArrayList<DpnIds>() ;
706         DpnIdsBuilder builder = new DpnIdsBuilder() ;
707         for( BigInteger dpnId : dpnIds) {
708             dpnIdList.add(builder.setKey(new DpnIdsKey(dpnId)).setDPN(dpnId).build() );
709         }
710         return dpnIdList;
711     }
712
713     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
714         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder =
715                 InstanceIdentifier.builder(InterfacesState.class)
716                         .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.class,
717                                 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
718                                         interfaceName));
719         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> id = idBuilder.build();
720         return id;
721     }
722     public static Boolean readMonitoringStateFromDS(DataBroker dataBroker) {
723         InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
724         Optional<TunnelMonitorParams> TunnelMonitorParamsOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION,
725                 iid, dataBroker);
726         if(TunnelMonitorParamsOptional.isPresent())
727             return TunnelMonitorParamsOptional.get().isEnabled();
728         return null;
729     }
730
731     public static Integer readMonitorIntervalfromDS(DataBroker dataBroker) {
732         InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.create(TunnelMonitorInterval.class);
733         Optional<TunnelMonitorInterval> tunnelMonitorIOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
734         if(tunnelMonitorIOptional.isPresent())
735             return tunnelMonitorIOptional.get().getInterval();
736         return null;
737
738     }
739
740     public static Integer determineMonitorInterval(DataBroker dataBroker) {
741         Integer monitorInterval = ItmUtils.readMonitorIntervalfromDS(dataBroker);
742         LOG.debug("determineMonitorInterval: monitorInterval from DS = {}", monitorInterval);
743         if(monitorInterval==null){
744             Class<? extends TunnelMonitoringTypeBase> monitoringProtocol = determineMonitorProtocol(dataBroker);
745             if(monitoringProtocol.getName().contains("Bfd"))
746                 monitorInterval = ITMConstants.BFD_DEFAULT_MONITOR_INTERVAL;
747             else
748                 monitorInterval = ITMConstants.DEFAULT_MONITOR_INTERVAL;
749         }
750         LOG.debug("determineMonitorInterval: monitorInterval = {}", monitorInterval);
751         return monitorInterval;
752     }
753
754     public static List<String> getTunnelsofTzone(List<HwVtep> hwVteps, String tzone, DataBroker dataBroker, Boolean hwVtepsExist) {
755
756         List<String> tunnels = new ArrayList<String>();
757         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
758                 child(TransportZone.class, new TransportZoneKey(tzone)).build();
759         Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
760         Class<? extends TunnelTypeBase> tunType = tZoneOptional.get().getTunnelType();
761         if (tZoneOptional.isPresent()) {
762             if (tZoneOptional.get().getSubnets() != null && !tZoneOptional.get().getSubnets().isEmpty()) {
763                 for (Subnets sub : tZoneOptional.get().getSubnets()) {
764                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
765                         for (Vteps vtepLocal : sub.getVteps()) {
766                             for (Vteps vtepRemote : sub.getVteps()) {
767                                 if (!vtepLocal.equals(vtepRemote)) {
768                                     InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(), tunType);
769                                     InstanceIdentifier<InternalTunnel> intIID =
770                                             InstanceIdentifier.builder(TunnelList.class).
771                                                     child(InternalTunnel.class, key).build();
772                                     Optional<InternalTunnel> TunnelsOptional =
773                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
774                                     if (TunnelsOptional.isPresent()) {
775                                         LOG.trace("Internal Tunnel added {}",TunnelsOptional.get().getTunnelInterfaceName());
776                                         tunnels.add(TunnelsOptional.get().getTunnelInterfaceName());
777                                     }
778                                 }
779                             }
780                             if(hwVteps!= null && !hwVteps.isEmpty()) {
781                                 for (HwVtep hwVtep : hwVteps) {
782                                     tunnels.add(getExtTunnel(hwVtep.getNode_id(), vtepLocal.getDpnId().toString(),
783                                             tunType, dataBroker));
784                                     tunnels.add(getExtTunnel(vtepLocal.getDpnId().toString(), hwVtep.getNode_id(),
785                                             tunType, dataBroker));
786                                 }
787                             }
788                         }
789                     }
790                 }
791             }
792         }
793         if (hwVtepsExist) {
794             for (HwVtep hwVtep : hwVteps) {
795                 for (HwVtep hwVtepOther : hwVteps) {
796                     if (!hwVtep.getHwIp().equals(hwVtepOther.getHwIp())) {
797                         tunnels.add(getExtTunnel(hwVtep.getNode_id(), hwVtepOther.getNode_id(), tunType, dataBroker));
798                         tunnels.add(getExtTunnel(hwVtepOther.getNode_id(), hwVtep.getNode_id(), tunType, dataBroker));
799                     }
800                 }
801             }
802         }
803         return tunnels;
804     }
805
806     public static List<String> getInternalTunnelsofTzone(String tzone, DataBroker dataBroker) {
807         List<String> tunnels = new ArrayList<String>();
808         LOG.trace("Getting internal tunnels of {}",tzone);
809         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
810                 child(TransportZone.class, new TransportZoneKey(tzone)).build();
811         Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
812         if (tZoneOptional.isPresent()) {
813             if (tZoneOptional.get().getSubnets() != null && !tZoneOptional.get().getSubnets().isEmpty()) {
814                 for (Subnets sub : tZoneOptional.get().getSubnets()) {
815                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
816                         for (Vteps vtepLocal : sub.getVteps()) {
817                             for (Vteps vtepRemote : sub.getVteps()) {
818                                 if (!vtepLocal.equals(vtepRemote)) {
819                                     InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(), tZoneOptional.get().getTunnelType());
820                                     InstanceIdentifier<InternalTunnel> intIID =
821                                             InstanceIdentifier.builder(TunnelList.class).
822                                                     child(InternalTunnel.class, key).build();
823                                     Optional<InternalTunnel> TunnelsOptional =
824                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
825                                     if (TunnelsOptional.isPresent()) {
826                                         LOG.trace("Internal Tunnel added {}",
827                                                 TunnelsOptional.get().getTunnelInterfaceName());
828                                         tunnels.add(TunnelsOptional.get().getTunnelInterfaceName());
829                                     }
830                                 }
831                             }
832                         }
833                     }
834                 }
835             }
836         }
837         return tunnels;
838     }
839
840     private static String getExtTunnel(String node_id, String dpId,Class<? extends TunnelTypeBase> tunType, DataBroker dataBroker) {
841         LOG.trace("getting ext tunnel for {} and dpId {}",node_id,dpId);
842         ExternalTunnelKey key = getExternalTunnelKey(dpId, node_id, tunType);
843         InstanceIdentifier<ExternalTunnel> intIID = InstanceIdentifier.builder(ExternalTunnelList.class).
844                 child(ExternalTunnel.class, key).build();
845         Optional<ExternalTunnel> TunnelsOptional =
846                 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
847         if (TunnelsOptional.isPresent()) {
848             LOG.trace("ext tunnel returned {} ",TunnelsOptional.get().getTunnelInterfaceName());
849             return TunnelsOptional.get().getTunnelInterfaceName();
850         }
851         return null;
852     }
853     public static ExternalTunnelKey getExternalTunnelKey(String dst , String src, Class<? extends TunnelTypeBase> tunType) {
854         if (src.indexOf("physicalswitch") > 0) {
855             src = src.substring(0, src.indexOf("physicalswitch") - 1);
856         }
857         if (dst.indexOf("physicalswitch") > 0) {
858             dst = dst.substring(0, dst.indexOf("physicalswitch") - 1);
859         }
860         return new ExternalTunnelKey(dst, src, tunType);
861     }
862
863     public static List<TunnelEndPoints> getTEPsForDpn( BigInteger srcDpn, List<DPNTEPsInfo> dpnList) {
864         for (DPNTEPsInfo dpn : dpnList) {
865             if( dpn.getDPNID().equals(srcDpn)) {
866                 return dpn.getTunnelEndPoints() ;
867             }
868         }
869         return null ;
870     }
871     public static TunnelList getAllInternalTunnels(DataBroker broker) {
872         InstanceIdentifier<TunnelList> tunnelListInstanceIdentifier = InstanceIdentifier.builder(TunnelList.class).build();
873         Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, tunnelListInstanceIdentifier, broker);
874         if (tunnelList.isPresent()) {
875             return tunnelList.get();
876         }
877         return null;
878     }
879     public static InternalTunnel getInternalTunnel(String interfaceName, DataBroker broker) {
880         InternalTunnel internalTunnel = null;
881         TunnelList tunnelList = getAllInternalTunnels(broker);
882         if (tunnelList != null && tunnelList.getInternalTunnel() != null) {
883             List<InternalTunnel> internalTunnels = tunnelList.getInternalTunnel();
884             for (InternalTunnel tunnel : internalTunnels) {
885                 if (tunnel.getTunnelInterfaceName().equalsIgnoreCase(interfaceName)) {
886                     internalTunnel = tunnel;
887                     break;
888                 }
889             }
890         }
891         return internalTunnel;
892     }
893     public static ExternalTunnel getExternalTunnel(String interfaceName, DataBroker broker) {
894         ExternalTunnel externalTunnel = null;
895         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker);
896         for (ExternalTunnel tunnel : externalTunnels) {
897             if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
898                 externalTunnel = tunnel;
899                 break;
900             }
901         }
902         return externalTunnel;
903     }
904     public static List<ExternalTunnel> getAllExternalTunnels(DataBroker broker) {
905         List<ExternalTunnel> result = null;
906         InstanceIdentifier<ExternalTunnelList> id = InstanceIdentifier.builder(ExternalTunnelList.class).build();
907         Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, id, broker);
908         if (tunnelList.isPresent()) {
909             result = tunnelList.get().getExternalTunnel();
910         }
911         if (result == null) {
912             result = Collections.emptyList();
913         }
914         return result;
915     }
916     public static String convertTunnelTypetoString(Class<? extends TunnelTypeBase> tunType ) {
917         String tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
918         if( tunType.equals(TunnelTypeVxlan.class))
919             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN ;
920         else if( tunType.equals(TunnelTypeGre.class) )
921             tunnelType = ITMConstants.TUNNEL_TYPE_GRE ;
922         else if (tunnelType.equals(TunnelTypeMplsOverGre.class))
923             tunnelType = ITMConstants.TUNNEL_TYPE_MPLS_OVER_GRE;
924         return tunnelType ;
925     }
926
927
928     public static boolean isItmIfType(Class<? extends InterfaceType> ifType) {
929         if( (ifType != null) && (ifType.isAssignableFrom(Tunnel.class)) ) {
930             return true;
931         }
932         return false;
933     }
934
935     public static StateTunnelListKey getTunnelStateKey( org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface iface) {
936         StateTunnelListKey key = null;
937         if(isItmIfType(iface.getType())) {
938             key = new StateTunnelListKey(iface.getName());
939         }
940         return key;
941     }
942
943     public static void updateTunnelsCache(DataBroker broker) {
944         List<InternalTunnel> internalTunnels = getAllInternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
945         for (InternalTunnel tunnel : internalTunnels) {
946             itmCache.addInternalTunnel(tunnel);
947         }
948         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
949         for (ExternalTunnel tunnel : externalTunnels) {
950             itmCache.addExternalTunnel(tunnel);
951         }
952     }
953
954     public static List<ExternalTunnel> getAllExternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
955         List<ExternalTunnel> result = null;
956         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
957         Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
958         if (tunnelList.isPresent()) {
959             result = tunnelList.get().getExternalTunnel();
960         }
961         if (result == null) {
962             result = Collections.emptyList();
963         }
964         return result;
965     }
966
967     public static List<InternalTunnel> getAllInternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
968         List<InternalTunnel> result = null;
969         InstanceIdentifier<TunnelList> iid = InstanceIdentifier.builder(TunnelList.class).build();
970         Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
971         if (tunnelList.isPresent()) {
972             result = tunnelList.get().getInternalTunnel();
973         }
974         if (result == null) {
975             result = Collections.emptyList();
976         }
977         return result;
978     }
979
980     public static Interface getInterface(
981             String name, DataBroker broker) {
982         Interface result = itmCache.getInterface(name);
983         if (result == null) {
984             InstanceIdentifier<Interface> iid =
985                     InstanceIdentifier.builder(Interfaces.class)
986                             .child(Interface.class, new InterfaceKey(name)).build();
987             Optional<Interface> optInterface = read(LogicalDatastoreType.CONFIGURATION, iid, broker);
988             if (optInterface.isPresent()) {
989                 result = optInterface.get();
990                 itmCache.addInterface(result);
991             }
992         }
993         return result;
994     }
995
996     public static Class<? extends TunnelMonitoringTypeBase> readMonitoringProtocolFromDS(DataBroker dataBroker) {
997         InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
998         Optional<TunnelMonitorParams> TunnelMonitorParamsOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION,
999                 iid, dataBroker);
1000         if(TunnelMonitorParamsOptional.isPresent())
1001             return TunnelMonitorParamsOptional.get().getMonitorProtocol();
1002         return null;
1003     }
1004
1005     public static Class<? extends TunnelMonitoringTypeBase> determineMonitorProtocol(DataBroker dataBroker) {
1006         Class<? extends TunnelMonitoringTypeBase> monitoringProtocol = ItmUtils.readMonitoringProtocolFromDS(dataBroker);
1007         LOG.debug("determineMonitorProtocol: monitorProtocol from DS = {}", monitoringProtocol);
1008         if(monitoringProtocol==null)
1009             monitoringProtocol = ITMConstants.DEFAULT_MONITOR_PROTOCOL;
1010         LOG.debug("determineMonitorProtocol: monitorProtocol = {}", monitoringProtocol);
1011         return monitoringProtocol;
1012     }
1013 }