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