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