Syncing the bug fixes that went in vpnservice after the initial porting of
[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.op.rev160406.tunnels_state.StateTunnelListKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.*;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.*;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeGre;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifier;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierKey;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorEnabled;
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, 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         Long monitoringInterval = (long) ITMConstants.DEFAULT_MONITOR_INTERVAL;
245         Boolean monitoringEnabled = true;
246         if(monitorInterval!= null)
247             monitoringInterval = monitorInterval.longValue();
248         if(monitorEnabled!=null  )
249             monitoringEnabled = monitorEnabled;
250         IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(remoteIp).setTunnelGateway(
251                 gatewayIp).setTunnelSource(localIp)
252                 .setTunnelInterfaceType(tunType).setInternal(internal).setMonitorEnabled(
253                         monitoringEnabled).setMonitorInterval(monitoringInterval).build();
254         builder.addAugmentation(IfTunnel.class, tunnel);
255         return builder.build();
256     }
257
258     public static Interface buildHwTunnelInterface(String tunnelIfName, String desc, boolean enabled, String topo_id,
259                                                    String node_id, Class<? extends TunnelTypeBase> tunType, IpAddress srcIp, IpAddress destIp,
260                                                    IpAddress gWIp, Boolean monitor_enabled, Integer monitor_interval){
261         InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(tunnelIfName)).setName(
262                 tunnelIfName).setDescription(desc).
263                 setEnabled(enabled).setType(Tunnel.class);
264         List<NodeIdentifier> nodeIds = new ArrayList<NodeIdentifier>();
265         NodeIdentifier hWnode = new NodeIdentifierBuilder().setKey(new NodeIdentifierKey(topo_id)).setTopologyId(
266                 topo_id).
267                 setNodeId(node_id).build();
268         nodeIds.add(hWnode);
269         ParentRefs parent = new ParentRefsBuilder().setNodeIdentifier(nodeIds).build();
270         builder.addAugmentation(ParentRefs.class, parent);
271         Long monitoringInterval = (long) ITMConstants.DEFAULT_MONITOR_INTERVAL;
272         Boolean monitoringEnabled = true;
273         if(monitor_interval!= null)
274             monitoringInterval = monitor_interval.longValue();
275         if(monitor_enabled!=null  )
276             monitoringEnabled = monitor_enabled;
277         IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(destIp).setTunnelGateway(gWIp).setTunnelSource(
278                 srcIp).setMonitorEnabled(monitoringEnabled).setMonitorInterval(100L).
279                 setTunnelInterfaceType(tunType).setInternal(false).build();
280         builder.addAugmentation(IfTunnel.class, tunnel);
281         LOG.trace("iftunnel {} built from hwvtep {} ", tunnel, node_id);
282         return builder.build();
283     }
284
285
286     public static InternalTunnel buildInternalTunnel( BigInteger srcDpnId, BigInteger dstDpnId,
287                                                       Class<? extends TunnelTypeBase> tunType,
288                                                       String trunkInterfaceName) {
289         InternalTunnel tnl = new InternalTunnelBuilder().setKey(new InternalTunnelKey(dstDpnId, srcDpnId, tunType)).setDestinationDPN(dstDpnId)
290                 .setSourceDPN(srcDpnId).setTransportType(tunType)
291                 .setTunnelInterfaceName(trunkInterfaceName).build();
292         return tnl ;
293     }
294
295     public static ExternalTunnel buildExternalTunnel(String srcNode, String dstNode,
296                                                      Class<? extends TunnelTypeBase> tunType,
297                                                      String trunkInterfaceName) {
298         ExternalTunnel extTnl = new ExternalTunnelBuilder().setKey(
299                 new ExternalTunnelKey(dstNode, srcNode, tunType))
300                 .setSourceDevice(srcNode).setDestinationDevice(dstNode)
301                 .setTunnelInterfaceName(trunkInterfaceName)
302                 .setTransportType(tunType).build();
303         return extTnl ;
304     }
305
306     public static List<DPNTEPsInfo> getTunnelMeshInfo(DataBroker dataBroker) {
307         List<DPNTEPsInfo> dpnTEPs= null ;
308
309         // Read the EndPoint Info from the operational database
310         InstanceIdentifierBuilder<DpnEndpoints> depBuilder = InstanceIdentifier.builder( DpnEndpoints.class);
311         InstanceIdentifier<DpnEndpoints> deps = depBuilder.build();
312         Optional<DpnEndpoints> dpnEps = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, deps, dataBroker);
313         if (dpnEps.isPresent()) {
314             DpnEndpoints tn= dpnEps.get() ;
315             dpnTEPs = tn.getDPNTEPsInfo();
316             LOG.debug( "Read from CONFIGURATION datastore - No. of Dpns " , dpnTEPs.size() );
317         }else
318             LOG.debug( "No Dpn information in CONFIGURATION datastore "  );
319         return dpnTEPs ;
320     }
321
322     public static int getUniqueId(IdManagerService idManager, String idKey) {
323         AllocateIdInput getIdInput = new AllocateIdInputBuilder()
324                 .setPoolName(ITMConstants.ITM_IDPOOL_NAME)
325                 .setIdKey(idKey).build();
326
327         try {
328             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
329             RpcResult<AllocateIdOutput> rpcResult = result.get();
330             if(rpcResult.isSuccessful()) {
331                 return rpcResult.getResult().getIdValue().intValue();
332             } else {
333                 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
334             }
335         } catch (InterruptedException | ExecutionException e) {
336             LOG.warn("Exception when getting Unique Id",e);
337         }
338         return 0;
339     }
340
341     public static void releaseId(IdManagerService idManager, String idKey) {
342         ReleaseIdInput idInput =
343                 new ReleaseIdInputBuilder().setPoolName(ITMConstants.ITM_IDPOOL_NAME).setIdKey(idKey).build();
344         try {
345             Future<RpcResult<Void>> result = idManager.releaseId(idInput);
346             RpcResult<Void> rpcResult = result.get();
347             if(!rpcResult.isSuccessful()) {
348                 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
349             }
350         } catch (InterruptedException | ExecutionException e) {
351             LOG.warn("Exception when getting Unique Id for key {}", idKey, e);
352         }
353     }
354
355     public static List<DPNTEPsInfo> getDPNTEPListFromDPNId(DataBroker dataBroker, List<BigInteger> dpnIds) {
356         List<DPNTEPsInfo> meshedDpnList = getTunnelMeshInfo(dataBroker) ;
357         List<DPNTEPsInfo> cfgDpnList = new ArrayList<DPNTEPsInfo>();
358         if( null != meshedDpnList) {
359             for(BigInteger dpnId : dpnIds) {
360                 for( DPNTEPsInfo teps : meshedDpnList ) {
361                     if( dpnId.equals(teps.getDPNID()))
362                         cfgDpnList.add( teps) ;
363                 }
364             }
365         }
366         return cfgDpnList;
367     }
368
369     public static void setUpOrRemoveTerminatingServiceTable(BigInteger dpnId, IMdsalApiManager mdsalManager, boolean addFlag) {
370         String logmsg = ( addFlag == true) ? "Installing" : "Removing";
371         LOG.trace( logmsg + " PUNT to Controller flow in DPN {} ", dpnId );
372         long dpId;
373         List<ActionInfo> listActionInfo = new ArrayList<ActionInfo>();
374         listActionInfo.add(new ActionInfo(ActionType.punt_to_controller,
375                 new String[] {}));
376
377         try {
378             List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
379
380             mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {
381                     BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID) }));
382
383             List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>();
384             mkInstructions.add(new InstructionInfo(InstructionType.apply_actions,
385                     listActionInfo));
386
387             FlowEntity terminatingServiceTableFlowEntity = MDSALUtil
388                     .buildFlowEntity(
389                             dpnId,
390                             NwConstants.INTERNAL_TUNNEL_TABLE,
391                             getFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE,
392                                     ITMConstants.LLDP_SERVICE_ID), 5, String.format("%s:%d","ITM Flow Entry ",ITMConstants.LLDP_SERVICE_ID),
393                             0, 0, ITMConstants.COOKIE_ITM
394                                     .add(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)),
395                             mkMatches, mkInstructions);
396             if(addFlag)
397                 mdsalManager.installFlow(terminatingServiceTableFlowEntity);
398             else
399                 mdsalManager.removeFlow(terminatingServiceTableFlowEntity);
400         } catch (Exception e) {
401             LOG.error("Error while setting up Table 36 for {}", dpnId, e);
402         }
403     }
404
405     private static String getFlowRef(long termSvcTable, int svcId) {
406         return new StringBuffer().append(termSvcTable).append(svcId).toString();
407     }
408     public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier(String schemaName) {
409         return InstanceIdentifier.builder(VtepConfigSchemas.class)
410                 .child(VtepConfigSchema.class, new VtepConfigSchemaKey(schemaName)).build();
411     }
412
413     public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier() {
414         return InstanceIdentifier.builder(VtepConfigSchemas.class).child(VtepConfigSchema.class).build();
415     }
416     public static InstanceIdentifier<VtepConfigSchemas> getVtepConfigSchemasIdentifier() {
417         return InstanceIdentifier.builder(VtepConfigSchemas.class).build();
418     }
419     public static InstanceIdentifier<VtepIpPool> getVtepIpPoolIdentifier(String subnetCidr) {
420         return InstanceIdentifier.builder(VtepIpPools.class).child(VtepIpPool.class, new VtepIpPoolKey(subnetCidr))
421                 .build();
422     }
423     public static VtepConfigSchema validateForAddVtepConfigSchema(VtepConfigSchema schema,
424                                                                   List<VtepConfigSchema> existingSchemas) {
425         VtepConfigSchema validSchema = validateVtepConfigSchema(schema);
426         for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
427             if (!StringUtils.equalsIgnoreCase(schema.getSchemaName(), existingSchema.getSchemaName())
428                     && schema.getSubnet().equals(existingSchema.getSubnet())) {
429                 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
430                 Preconditions.checkArgument(false, new StringBuilder("VTEP schema with subnet [").append(subnetCidr)
431                         .append("] already exists. Multiple VTEP schemas with same subnet is not allowed.").toString());
432             }
433         }
434         if (isNotEmpty(getDpnIdList(validSchema.getDpnIds()))) {
435             String tzone = validSchema.getTransportZoneName();
436             List<BigInteger> lstDpns = getConflictingDpnsAlreadyConfiguredWithTz(validSchema.getSchemaName(), tzone,
437                     getDpnIdList(validSchema.getDpnIds()), existingSchemas);
438             if (!lstDpns.isEmpty()) {
439                 Preconditions.checkArgument(false,
440                         new StringBuilder("DPN's ").append(lstDpns).append(" already configured for transport zone ")
441                                 .append(tzone).append(". Only one end point per transport Zone per Dpn is allowed.")
442                                 .toString());
443             }
444             if (schema.getTunnelType().equals(TunnelTypeGre.class)){
445                 validateForSingleGreTep(validSchema.getSchemaName(), getDpnIdList(validSchema.getDpnIds()), existingSchemas);
446             }
447         }
448         return validSchema;
449     }
450     private static void validateForSingleGreTep(String schemaName, List<BigInteger> lstDpnsForAdd,
451                                                 List<VtepConfigSchema> existingSchemas) {
452         for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
453             if ((TunnelTypeGre.class).equals(existingSchema.getTunnelType())
454                     && !StringUtils.equalsIgnoreCase(schemaName, existingSchema.getSchemaName())) {
455                 List<BigInteger> lstConflictingDpns = new ArrayList<>(getDpnIdList(existingSchema.getDpnIds()));
456                 lstConflictingDpns.retainAll(emptyIfNull(lstDpnsForAdd));
457                 if (!lstConflictingDpns.isEmpty()) {
458                     String errMsg = new StringBuilder("DPN's ").append(lstConflictingDpns)
459                             .append(" already configured with GRE TEP. Mutiple GRE TEP's on a single DPN are not allowed.")
460                             .toString();
461                     Preconditions.checkArgument(false, errMsg);
462                 }
463             }
464         }
465     }
466     public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
467         Preconditions.checkNotNull(schema);
468         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
469         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
470         Preconditions.checkArgument((schema.getVlanId() >= 0 && schema.getVlanId() < 4095),
471                 "Invalid VLAN ID, range (0-4094)");
472         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
473         Preconditions.checkNotNull(schema.getSubnet());
474         String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
475         SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
476         IpAddress gatewayIp = schema.getGatewayIp();
477         if (gatewayIp != null) {
478             String strGatewayIp = String.valueOf(gatewayIp.getValue());
479             if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS) && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
480                 Preconditions.checkArgument(false, new StringBuilder("Gateway IP address ").append(strGatewayIp)
481                         .append(" is not in subnet range ").append(subnetCidr).toString());
482             }
483         }
484         ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
485         return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
486     }
487     public static String validateTunnelType(String tunnelType) {
488         if (tunnelType == null) {
489             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
490         } else {
491             tunnelType = StringUtils.upperCase(tunnelType);
492             String error = new StringBuilder("Invalid tunnel type. Valid values: ")
493                     .append(ITMConstants.TUNNEL_TYPE_VXLAN).append(" | ").append(ITMConstants.TUNNEL_TYPE_GRE)
494                     .toString();
495             Preconditions.checkArgument(ITMConstants.TUNNEL_TYPE_VXLAN.equals(tunnelType)
496                     || ITMConstants.TUNNEL_TYPE_GRE.equals(tunnelType), error);
497         }
498         return tunnelType;
499     }
500     private static List<BigInteger> getConflictingDpnsAlreadyConfiguredWithTz(String schemaName, String tzone,
501                                                                               List<BigInteger> lstDpns, List<VtepConfigSchema> existingSchemas) {
502         List<BigInteger> lstConflictingDpns = new ArrayList<>();
503         for (VtepConfigSchema schema : emptyIfNull(existingSchemas)) {
504             if (!StringUtils.equalsIgnoreCase(schemaName, schema.getSchemaName())
505                     && StringUtils.equals(schema.getTransportZoneName(), tzone)) {
506                 lstConflictingDpns = new ArrayList<>(getDpnIdList(schema.getDpnIds()));
507                 lstConflictingDpns.retainAll(lstDpns);
508                 if (!lstConflictingDpns.isEmpty()) {
509                     break;
510                 }
511             }
512         }
513         return lstConflictingDpns;
514     }
515     public static VtepConfigSchema constructVtepConfigSchema(String schemaName, String portName, Integer vlanId,
516                                                              String subnetMask, String gatewayIp, String transportZone,String tunnelType, List<BigInteger> dpnIds,
517                                                              String excludeIpFilter) {
518         IpAddress gatewayIpObj = StringUtils.isBlank(gatewayIp) ? null : new IpAddress(gatewayIp.toCharArray());
519         IpPrefix subnet = StringUtils.isBlank(subnetMask) ? null : new IpPrefix(subnetMask.toCharArray());
520         Class<? extends TunnelTypeBase> tunType ;
521         if( tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN))
522             tunType = TunnelTypeVxlan.class ;
523         else
524             tunType = TunnelTypeGre.class ;
525         VtepConfigSchemaBuilder schemaBuilder = new VtepConfigSchemaBuilder().setSchemaName(schemaName)
526                 .setPortName(portName).setVlanId(vlanId).setSubnet(subnet).setGatewayIp(gatewayIpObj)
527                 .setTransportZoneName(transportZone).setTunnelType(tunType).setDpnIds(getDpnIdsListFromBigInt(dpnIds))
528                 .setExcludeIpFilter(excludeIpFilter);
529         return schemaBuilder.build();
530     }
531     public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
532         final List<IpAddress> lstIpAddress = new ArrayList<>();
533         if (StringUtils.isBlank(excludeIpFilter)) {
534             return lstIpAddress;
535         }
536         final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
537         for (String ip : arrIps) {
538             if (StringUtils.countMatches(ip, "-") == 1) {
539                 final String[] arrIpRange = StringUtils.split(ip, '-');
540                 String strStartIp = StringUtils.trim(arrIpRange[0]);
541                 String strEndIp = StringUtils.trim(arrIpRange[1]);
542                 Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
543                         new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strStartIp)
544                                 .toString());
545                 Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
546                         new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strEndIp)
547                                 .toString());
548                 Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
549                         new StringBuilder("Invalid exclude IP filter: IP address [").append(strStartIp)
550                                 .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
551                 Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
552                         new StringBuilder("Invalid exclude IP filter: IP address [").append(strEndIp)
553                                 .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
554                 int startIp = subnetInfo.asInteger(strStartIp);
555                 int endIp = subnetInfo.asInteger(strEndIp);
556
557                 Preconditions.checkArgument(startIp < endIp,
558                         new StringBuilder("Invalid exclude IP filter: Invalid range [").append(ip).append("] ")
559                                 .toString());
560                 for (int i = startIp; i <= endIp; i++) {
561                     String ipAddress = ipFormat(toIpArray(i));
562                     validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
563                 }
564             } else {
565                 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
566             }
567         }
568         return lstIpAddress;
569     }
570     private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
571                                                       String ipAddress) {
572         String ip = StringUtils.trim(ipAddress);
573         Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
574                 new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(ip).toString());
575         Preconditions.checkArgument(subnetInfo.isInRange(ip),
576                 new StringBuilder("Invalid exclude IP filter: IP address [").append(ip).append("] not in subnet range ")
577                         .append(subnetInfo.getCidrSignature()).toString());
578         lstIpAddress.add(new IpAddress(ip.toCharArray()));
579     }
580     private static int[] toIpArray(int val) {
581         int[] ret = new int[4];
582         for (int j = 3; j >= 0; --j) {
583             ret[j] |= ((val >>> 8 * (3 - j)) & (0xff));
584         }
585         return ret;
586     }
587     private static String ipFormat(int[] octets) {
588         StringBuilder str = new StringBuilder();
589         for (int i = 0; i < octets.length; ++i) {
590             str.append(octets[i]);
591             if (i != octets.length - 1) {
592                 str.append(".");
593             }
594         }
595         return str.toString();
596     }
597     public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd,
598                                                                List<BigInteger> lstDpnsForDelete, IITMProvider itmProvider) {
599         Preconditions.checkArgument(StringUtils.isNotBlank(schemaName));
600         if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty())
601                 && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) {
602             Preconditions.checkArgument(false,
603                     new StringBuilder("DPN ID list for add | delete is null or empty in schema ").append(schemaName)
604                             .toString());
605         }
606         VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName);
607         if (schema == null) {
608             Preconditions.checkArgument(false, new StringBuilder("Specified VTEP Schema [").append(schemaName)
609                     .append("] doesn't exists!").toString());
610         }
611         List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds());
612         if (isNotEmpty(lstDpnsForAdd)) {
613             if (isNotEmpty(existingDpnIds)) {
614                 List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds);
615                 lstAlreadyExistingDpns.retainAll(lstDpnsForAdd);
616                 Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(),
617                         new StringBuilder("DPN ID's ").append(lstAlreadyExistingDpns)
618                                 .append(" already exists in VTEP schema [").append(schemaName).append("]").toString());
619             }
620             if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
621                 validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd, itmProvider.getAllVtepConfigSchemas());
622             }
623         }
624         if (isNotEmpty(lstDpnsForDelete)) {
625             if (existingDpnIds == null || existingDpnIds.isEmpty()) {
626                 StringBuilder builder = new StringBuilder("DPN ID's ").append(lstDpnsForDelete)
627                         .append(" specified for delete from VTEP schema [").append(schemaName)
628                         .append("] are not configured in the schema.");
629                 Preconditions.checkArgument(false, builder.toString());
630             } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) {
631                 List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete);
632                 lstConflictingDpns.removeAll(existingDpnIds);
633                 StringBuilder builder = new StringBuilder("DPN ID's ").append(lstConflictingDpns)
634                         .append(" specified for delete from VTEP schema [").append(schemaName)
635                         .append("] are not configured in the schema.");
636                 Preconditions.checkArgument(false, builder.toString());
637             }
638         }
639         return schema;
640     }
641     public static String getSubnetCidrAsString(IpPrefix subnet) {
642         return (subnet == null) ? StringUtils.EMPTY : String.valueOf(subnet.getValue());
643     }
644     public static <T> List<T> emptyIfNull(List<T> list) {
645         return (list == null) ? Collections.<T> emptyList() : list;
646     }
647     public static <T> boolean isEmpty(Collection<T> collection) {
648         return (collection == null || collection.isEmpty()) ? true : false;
649     }
650     public static <T> boolean isNotEmpty(Collection<T> collection) {
651         return !isEmpty(collection);
652     }
653     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) {
654         HwVtep hwVtep = new HwVtep();
655         hwVtep.setGatewayIP(gatewayIP);
656         hwVtep.setHwIp(ipAddress);
657         hwVtep.setIpPrefix(ipPrefix);
658         hwVtep.setNode_id(node_id);
659         hwVtep.setTopo_id(topo_id);
660         hwVtep.setTransportZone(transportZone.getZoneName());
661         hwVtep.setTunnel_type(tunnel_type);
662         hwVtep.setVlanID(vlanID);
663         return hwVtep;
664     }
665
666     public static String getHwParentIf(String topo_id, String srcNodeid) {
667         return String.format("%s:%s", topo_id, srcNodeid);
668     }
669
670     public static <T extends DataObject> void syncWrite(LogicalDatastoreType datastoreType,
671                                                         InstanceIdentifier<T> path, T data, DataBroker broker) {
672         WriteTransaction tx = broker.newWriteOnlyTransaction();
673         tx.put(datastoreType, path, data, true);
674         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
675         try {
676             futures.get();
677         } catch (InterruptedException | ExecutionException e) {
678             LOG.error("ITMUtils:SyncWrite , Error writing to datastore (path, data) : ({}, {})", path, data);
679             throw new RuntimeException(e.getMessage());
680         }
681     }
682
683     public static List<BigInteger> getDpnIdList( List<DpnIds> dpnIds ) {
684         List<BigInteger> dpnList = new ArrayList<BigInteger>() ;
685         for( DpnIds dpn : dpnIds) {
686             dpnList.add(dpn.getDPN()) ;
687         }
688         return dpnList ;
689     }
690
691     public static List<DpnIds> getDpnIdsListFromBigInt( List<BigInteger> dpnIds) {
692         List<DpnIds> dpnIdList = new ArrayList<DpnIds>() ;
693         DpnIdsBuilder builder = new DpnIdsBuilder() ;
694         for( BigInteger dpnId : dpnIds) {
695             dpnIdList.add(builder.setKey(new DpnIdsKey(dpnId)).setDPN(dpnId).build() );
696         }
697         return dpnIdList;
698     }
699
700     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
701         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder =
702                 InstanceIdentifier.builder(InterfacesState.class)
703                         .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.class,
704                                 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
705                                         interfaceName));
706         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> id = idBuilder.build();
707         return id;
708     }
709     public static Boolean readMonitoringStateFromDS(DataBroker dataBroker) {
710         InstanceIdentifier<TunnelMonitorEnabled> iid = InstanceIdentifier.create(TunnelMonitorEnabled.class);
711         Optional<TunnelMonitorEnabled> tunnelMonitorEnabledOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION,
712                 iid, dataBroker);
713         if(tunnelMonitorEnabledOptional.isPresent())
714             return tunnelMonitorEnabledOptional.get().isEnabled();
715         return null;
716     }
717
718     public static Integer readMonitorIntervalfromDS(DataBroker dataBroker) {
719         InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.create(TunnelMonitorInterval.class);
720         Optional<TunnelMonitorInterval> tunnelMonitorIOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
721         if(tunnelMonitorIOptional.isPresent())
722             return tunnelMonitorIOptional.get().getInterval();
723         return null;
724
725     }
726
727     public static List<String> getTunnelsofTzone(List<HwVtep> hwVteps, String tzone, DataBroker dataBroker, Boolean hwVtepsExist) {
728
729         List<String> tunnels = new ArrayList<String>();
730         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
731                 child(TransportZone.class, new TransportZoneKey(tzone)).build();
732         Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
733         Class<? extends TunnelTypeBase> tunType = tZoneOptional.get().getTunnelType();
734         if (tZoneOptional.isPresent()) {
735             if (tZoneOptional.get().getSubnets() != null && !tZoneOptional.get().getSubnets().isEmpty()) {
736                 for (Subnets sub : tZoneOptional.get().getSubnets()) {
737                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
738                         for (Vteps vtepLocal : sub.getVteps()) {
739                             for (Vteps vtepRemote : sub.getVteps()) {
740                                 if (!vtepLocal.equals(vtepRemote)) {
741                                     InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(), tunType);
742                                     InstanceIdentifier<InternalTunnel> intIID =
743                                             InstanceIdentifier.builder(TunnelList.class).
744                                                     child(InternalTunnel.class, key).build();
745                                     Optional<InternalTunnel> TunnelsOptional =
746                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
747                                     if (TunnelsOptional.isPresent()) {
748                                         LOG.trace("Internal Tunnel added {}",TunnelsOptional.get().getTunnelInterfaceName());
749                                         tunnels.add(TunnelsOptional.get().getTunnelInterfaceName());
750                                     }
751                                 }
752                             }
753                             if(hwVteps!= null && !hwVteps.isEmpty()) {
754                                 for (HwVtep hwVtep : hwVteps) {
755                                     tunnels.add(getExtTunnel(hwVtep.getNode_id(), vtepLocal.getDpnId().toString(),
756                                             tunType, dataBroker));
757                                     tunnels.add(getExtTunnel(vtepLocal.getDpnId().toString(), hwVtep.getNode_id(),
758                                             tunType, dataBroker));
759                                 }
760                             }
761                         }
762                     }
763                 }
764             }
765         }
766         if (hwVtepsExist) {
767             for (HwVtep hwVtep : hwVteps) {
768                 for (HwVtep hwVtepOther : hwVteps) {
769                     if (!hwVtep.getHwIp().equals(hwVtepOther.getHwIp())) {
770                         tunnels.add(getExtTunnel(hwVtep.getNode_id(), hwVtepOther.getNode_id(), tunType, dataBroker));
771                         tunnels.add(getExtTunnel(hwVtepOther.getNode_id(), hwVtep.getNode_id(), tunType, dataBroker));
772                     }
773                 }
774             }
775         }
776         return tunnels;
777     }
778
779     public static List<String> getInternalTunnelsofTzone(String tzone, DataBroker dataBroker) {
780         List<String> tunnels = new ArrayList<String>();
781         LOG.trace("Getting internal tunnels of {}",tzone);
782         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
783                 child(TransportZone.class, new TransportZoneKey(tzone)).build();
784         Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
785         if (tZoneOptional.isPresent()) {
786             if (tZoneOptional.get().getSubnets() != null && !tZoneOptional.get().getSubnets().isEmpty()) {
787                 for (Subnets sub : tZoneOptional.get().getSubnets()) {
788                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
789                         for (Vteps vtepLocal : sub.getVteps()) {
790                             for (Vteps vtepRemote : sub.getVteps()) {
791                                 if (!vtepLocal.equals(vtepRemote)) {
792                                     InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(), tZoneOptional.get().getTunnelType());
793                                     InstanceIdentifier<InternalTunnel> intIID =
794                                             InstanceIdentifier.builder(TunnelList.class).
795                                                     child(InternalTunnel.class, key).build();
796                                     Optional<InternalTunnel> TunnelsOptional =
797                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
798                                     if (TunnelsOptional.isPresent()) {
799                                         LOG.trace("Internal Tunnel added {}",
800                                                 TunnelsOptional.get().getTunnelInterfaceName());
801                                         tunnels.add(TunnelsOptional.get().getTunnelInterfaceName());
802                                     }
803                                 }
804                             }
805                         }
806                     }
807                 }
808             }
809         }
810         return tunnels;
811     }
812
813     private static String getExtTunnel(String node_id, String dpId,Class<? extends TunnelTypeBase> tunType, DataBroker dataBroker) {
814         LOG.trace("getting ext tunnel for {} and dpId {}",node_id,dpId);
815         ExternalTunnelKey key = getExternalTunnelKey(dpId,node_id, tunType);
816         InstanceIdentifier<ExternalTunnel> intIID = InstanceIdentifier.builder(ExternalTunnelList.class).
817                 child(ExternalTunnel.class, key).build();
818         Optional<ExternalTunnel> TunnelsOptional =
819                 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
820         if (TunnelsOptional.isPresent()) {
821             LOG.trace("ext tunnel returned {} ",TunnelsOptional.get().getTunnelInterfaceName());
822             return TunnelsOptional.get().getTunnelInterfaceName();
823         }
824         return null;
825     }
826     public static ExternalTunnelKey getExternalTunnelKey(String dst , String src, Class<? extends TunnelTypeBase> tunType) {
827         if (src.indexOf("physicalswitch") > 0) {
828             src = src.substring(0, src.indexOf("physicalswitch") - 1);
829         }
830         if (dst.indexOf("physicalswitch") > 0) {
831             dst = dst.substring(0, dst.indexOf("physicalswitch") - 1);
832         }
833         return new ExternalTunnelKey(dst, src, tunType);
834     }
835
836     public static List<TunnelEndPoints> getTEPsForDpn( BigInteger srcDpn, List<DPNTEPsInfo> dpnList) {
837         for (DPNTEPsInfo dpn : dpnList) {
838             if( dpn.getDPNID().equals(srcDpn)) {
839                 return dpn.getTunnelEndPoints() ;
840             }
841         }
842         return null ;
843     }
844     public static TunnelList getAllInternalTunnels(DataBroker broker) {
845         InstanceIdentifier<TunnelList> tunnelListInstanceIdentifier = InstanceIdentifier.builder(TunnelList.class).build();
846         Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, tunnelListInstanceIdentifier, broker);
847         if (tunnelList.isPresent()) {
848             return tunnelList.get();
849         }
850         return null;
851     }
852     public static InternalTunnel getInternalTunnel(String interfaceName, DataBroker broker) {
853         InternalTunnel internalTunnel = null;
854         TunnelList tunnelList = getAllInternalTunnels(broker);
855         if (tunnelList != null && tunnelList.getInternalTunnel() != null) {
856             List<InternalTunnel> internalTunnels = tunnelList.getInternalTunnel();
857             for (InternalTunnel tunnel : internalTunnels) {
858                 if (tunnel.getTunnelInterfaceName().equalsIgnoreCase(interfaceName)) {
859                     internalTunnel = tunnel;
860                     break;
861                 }
862             }
863         }
864         return internalTunnel;
865     }
866     public static ExternalTunnel getExternalTunnel(String interfaceName, DataBroker broker) {
867         ExternalTunnel externalTunnel = null;
868         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker);
869         for (ExternalTunnel tunnel : externalTunnels) {
870             if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
871                 externalTunnel = tunnel;
872                 break;
873             }
874         }
875         return externalTunnel;
876     }
877     public static List<ExternalTunnel> getAllExternalTunnels(DataBroker broker) {
878         List<ExternalTunnel> result = null;
879         InstanceIdentifier<ExternalTunnelList> id = InstanceIdentifier.builder(ExternalTunnelList.class).build();
880         Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, id, broker);
881         if (tunnelList.isPresent()) {
882             result = tunnelList.get().getExternalTunnel();
883         }
884         if (result == null) {
885             result = Collections.emptyList();
886         }
887         return result;
888     }
889     public static String convertTunnelTypetoString(Class<? extends TunnelTypeBase> tunType ) {
890         String tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
891         if( tunType.equals(TunnelTypeVxlan.class))
892             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN ;
893         else if( tunType.equals(TunnelTypeGre.class) )
894             tunnelType = ITMConstants.TUNNEL_TYPE_GRE ;
895         else if (tunnelType.equals(TunnelTypeMplsOverGre.class))
896             tunnelType = ITMConstants.TUNNEL_TYPE_MPLS_OVER_GRE;
897         return tunnelType ;
898     }
899
900
901     public static boolean isItmIfType(Class<? extends InterfaceType> ifType) {
902         if( (ifType != null) && (ifType.isAssignableFrom(Tunnel.class)) ) {
903             return true;
904         }
905         return false;
906     }
907
908     public static StateTunnelListKey getTunnelStateKey(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface iface) {
909         StateTunnelListKey key = null;
910         if(isItmIfType(iface.getType())) {
911             key = new StateTunnelListKey(iface.getName());
912         }
913         return key;
914     }
915
916     public static void updateTunnelsCache(DataBroker broker) {
917         List<InternalTunnel> internalTunnels = getAllInternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
918         for (InternalTunnel tunnel : internalTunnels) {
919             itmCache.addInternalTunnel(tunnel);
920         }
921         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
922         for (ExternalTunnel tunnel : externalTunnels) {
923             itmCache.addExternalTunnel(tunnel);
924         }
925     }
926
927     public static List<ExternalTunnel> getAllExternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
928         List<ExternalTunnel> result = null;
929         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
930         Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
931         if (tunnelList.isPresent()) {
932             result = tunnelList.get().getExternalTunnel();
933         }
934         if (result == null) {
935             result = Collections.emptyList();
936         }
937         return result;
938     }
939
940     public static List<InternalTunnel> getAllInternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
941         List<InternalTunnel> result = null;
942         InstanceIdentifier<TunnelList> iid = InstanceIdentifier.builder(TunnelList.class).build();
943         Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
944         if (tunnelList.isPresent()) {
945             result = tunnelList.get().getInternalTunnel();
946         }
947         if (result == null) {
948             result = Collections.emptyList();
949         }
950         return result;
951     }
952
953     public static Interface getInterface(
954             String name, DataBroker broker) {
955         Interface result = itmCache.getInterface(name);
956         if (result == null) {
957             InstanceIdentifier<Interface> iid =
958                     InstanceIdentifier.builder(Interfaces.class)
959                             .child(Interface.class, new InterfaceKey(name)).build();
960             Optional<Interface> optInterface = read(LogicalDatastoreType.CONFIGURATION, iid, broker);
961             if (optInterface.isPresent()) {
962                 result = optInterface.get();
963                 itmCache.addInterface(result);
964             }
965         }
966         return result;
967     }
968 }