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