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