1cb5fea849beb32036a8c3e730e7eefb8e704d6e
[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 == true) ? "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 new StringBuffer().append(termSvcTable).append(svcId).toString();
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, new StringBuilder("VTEP schema with subnet [").append(subnetCidr)
486                         .append("] already exists. Multiple VTEP schemas with same subnet is not allowed.").toString());
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                         new StringBuilder("DPN's ").append(lstDpns).append(" already configured for transport zone ")
496                                 .append(tzone).append(". Only one end point per transport Zone per Dpn is allowed.")
497                                 .toString());
498             }
499             if (schema.getTunnelType().equals(TunnelTypeGre.class)){
500                 validateForSingleGreTep(validSchema.getSchemaName(), getDpnIdList(validSchema.getDpnIds()), existingSchemas);
501             }
502         }
503         return validSchema;
504     }
505     private static void validateForSingleGreTep(String schemaName, List<BigInteger> lstDpnsForAdd,
506                                                 List<VtepConfigSchema> existingSchemas) {
507         for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
508             if ((TunnelTypeGre.class).equals(existingSchema.getTunnelType())
509                     && !StringUtils.equalsIgnoreCase(schemaName, existingSchema.getSchemaName())) {
510                 List<BigInteger> lstConflictingDpns = new ArrayList<>(getDpnIdList(existingSchema.getDpnIds()));
511                 lstConflictingDpns.retainAll(emptyIfNull(lstDpnsForAdd));
512                 if (!lstConflictingDpns.isEmpty()) {
513                     String errMsg = new StringBuilder("DPN's ").append(lstConflictingDpns)
514                             .append(" already configured with GRE TEP. Mutiple GRE TEP's on a single DPN are not allowed.")
515                             .toString();
516                     Preconditions.checkArgument(false, errMsg);
517                 }
518             }
519         }
520     }
521     public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
522         Preconditions.checkNotNull(schema);
523         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
524         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
525         Preconditions.checkArgument((schema.getVlanId() >= 0 && schema.getVlanId() < 4095),
526                 "Invalid VLAN ID, range (0-4094)");
527         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
528         Preconditions.checkNotNull(schema.getSubnet());
529         String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
530         SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
531         IpAddress gatewayIp = schema.getGatewayIp();
532         if (gatewayIp != null) {
533             String strGatewayIp = String.valueOf(gatewayIp.getValue());
534             if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS) && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
535                 Preconditions.checkArgument(false, new StringBuilder("Gateway IP address ").append(strGatewayIp)
536                         .append(" is not in subnet range ").append(subnetCidr).toString());
537             }
538         }
539         ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
540         return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
541     }
542     public static String validateTunnelType(String tunnelType) {
543         if (tunnelType == null) {
544             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
545         } else {
546             tunnelType = StringUtils.upperCase(tunnelType);
547             String error = new StringBuilder("Invalid tunnel type. Valid values: ")
548                     .append(ITMConstants.TUNNEL_TYPE_VXLAN).append(" | ").append(ITMConstants.TUNNEL_TYPE_GRE)
549                     .toString();
550             Preconditions.checkArgument(ITMConstants.TUNNEL_TYPE_VXLAN.equals(tunnelType)
551                     || ITMConstants.TUNNEL_TYPE_GRE.equals(tunnelType), error);
552         }
553         return tunnelType;
554     }
555     private static List<BigInteger> getConflictingDpnsAlreadyConfiguredWithTz(String schemaName, String tzone,
556                                                                               List<BigInteger> lstDpns, List<VtepConfigSchema> existingSchemas) {
557         List<BigInteger> lstConflictingDpns = new ArrayList<>();
558         for (VtepConfigSchema schema : emptyIfNull(existingSchemas)) {
559             if (!StringUtils.equalsIgnoreCase(schemaName, schema.getSchemaName())
560                     && StringUtils.equals(schema.getTransportZoneName(), tzone)) {
561                 lstConflictingDpns = new ArrayList<>(getDpnIdList(schema.getDpnIds()));
562                 lstConflictingDpns.retainAll(lstDpns);
563                 if (!lstConflictingDpns.isEmpty()) {
564                     break;
565                 }
566             }
567         }
568         return lstConflictingDpns;
569     }
570     public static VtepConfigSchema constructVtepConfigSchema(String schemaName, String portName, Integer vlanId,
571                                                              String subnetMask, String gatewayIp, String transportZone,String tunnelType, List<BigInteger> dpnIds,
572                                                              String excludeIpFilter) {
573         IpAddress gatewayIpObj = StringUtils.isBlank(gatewayIp) ? null : new IpAddress(gatewayIp.toCharArray());
574         IpPrefix subnet = StringUtils.isBlank(subnetMask) ? null : new IpPrefix(subnetMask.toCharArray());
575         Class<? extends TunnelTypeBase> tunType ;
576         if( tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN))
577             tunType = TunnelTypeVxlan.class ;
578         else
579             tunType = TunnelTypeGre.class ;
580         VtepConfigSchemaBuilder schemaBuilder = new VtepConfigSchemaBuilder().setSchemaName(schemaName)
581                 .setPortName(portName).setVlanId(vlanId).setSubnet(subnet).setGatewayIp(gatewayIpObj)
582                 .setTransportZoneName(transportZone).setTunnelType(tunType).setDpnIds(getDpnIdsListFromBigInt(dpnIds))
583                 .setExcludeIpFilter(excludeIpFilter);
584         return schemaBuilder.build();
585     }
586     public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
587         final List<IpAddress> lstIpAddress = new ArrayList<>();
588         if (StringUtils.isBlank(excludeIpFilter)) {
589             return lstIpAddress;
590         }
591         final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
592         for (String ip : arrIps) {
593             if (StringUtils.countMatches(ip, "-") == 1) {
594                 final String[] arrIpRange = StringUtils.split(ip, '-');
595                 String strStartIp = StringUtils.trim(arrIpRange[0]);
596                 String strEndIp = StringUtils.trim(arrIpRange[1]);
597                 Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
598                         new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strStartIp)
599                                 .toString());
600                 Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
601                         new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strEndIp)
602                                 .toString());
603                 Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
604                         new StringBuilder("Invalid exclude IP filter: IP address [").append(strStartIp)
605                                 .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
606                 Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
607                         new StringBuilder("Invalid exclude IP filter: IP address [").append(strEndIp)
608                                 .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
609                 int startIp = subnetInfo.asInteger(strStartIp);
610                 int endIp = subnetInfo.asInteger(strEndIp);
611
612                 Preconditions.checkArgument(startIp < endIp,
613                         new StringBuilder("Invalid exclude IP filter: Invalid range [").append(ip).append("] ")
614                                 .toString());
615                 for (int i = startIp; i <= endIp; i++) {
616                     String ipAddress = ipFormat(toIpArray(i));
617                     validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
618                 }
619             } else {
620                 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
621             }
622         }
623         return lstIpAddress;
624     }
625     private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
626                                                       String ipAddress) {
627         String ip = StringUtils.trim(ipAddress);
628         Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
629                 new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(ip).toString());
630         Preconditions.checkArgument(subnetInfo.isInRange(ip),
631                 new StringBuilder("Invalid exclude IP filter: IP address [").append(ip).append("] not in subnet range ")
632                         .append(subnetInfo.getCidrSignature()).toString());
633         lstIpAddress.add(new IpAddress(ip.toCharArray()));
634     }
635     private static int[] toIpArray(int val) {
636         int[] ret = new int[4];
637         for (int j = 3; j >= 0; --j) {
638             ret[j] |= ((val >>> 8 * (3 - j)) & (0xff));
639         }
640         return ret;
641     }
642     private static String ipFormat(int[] octets) {
643         StringBuilder str = new StringBuilder();
644         for (int i = 0; i < octets.length; ++i) {
645             str.append(octets[i]);
646             if (i != octets.length - 1) {
647                 str.append(".");
648             }
649         }
650         return str.toString();
651     }
652     public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd,
653                                                                List<BigInteger> lstDpnsForDelete, IITMProvider itmProvider) {
654         Preconditions.checkArgument(StringUtils.isNotBlank(schemaName));
655         if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty())
656                 && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) {
657             Preconditions.checkArgument(false,
658                     new StringBuilder("DPN ID list for add | delete is null or empty in schema ").append(schemaName)
659                             .toString());
660         }
661         VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName);
662         if (schema == null) {
663             Preconditions.checkArgument(false, new StringBuilder("Specified VTEP Schema [").append(schemaName)
664                     .append("] doesn't exists!").toString());
665         }
666         List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds());
667         if (isNotEmpty(lstDpnsForAdd)) {
668             //  if (isNotEmpty(existingDpnIds)) {
669             List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds);
670             lstAlreadyExistingDpns.retainAll(lstDpnsForAdd);
671             Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(),
672                     new StringBuilder("DPN ID's ").append(lstAlreadyExistingDpns)
673                             .append(" already exists in VTEP schema [").append(schemaName).append("]").toString());
674             //    }
675             if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
676                 validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd, itmProvider.getAllVtepConfigSchemas());
677             }
678         }
679         if (isNotEmpty(lstDpnsForDelete)) {
680             if (existingDpnIds == null || existingDpnIds.isEmpty()) {
681                 StringBuilder builder = new StringBuilder("DPN ID's ").append(lstDpnsForDelete)
682                         .append(" specified for delete from VTEP schema [").append(schemaName)
683                         .append("] are not configured in the schema.");
684                 Preconditions.checkArgument(false, builder.toString());
685             } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) {
686                 List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete);
687                 lstConflictingDpns.removeAll(existingDpnIds);
688                 StringBuilder builder = new StringBuilder("DPN ID's ").append(lstConflictingDpns)
689                         .append(" specified for delete from VTEP schema [").append(schemaName)
690                         .append("] are not configured in the schema.");
691                 Preconditions.checkArgument(false, builder.toString());
692             }
693         }
694         return schema;
695     }
696     public static String getSubnetCidrAsString(IpPrefix subnet) {
697         return (subnet == null) ? StringUtils.EMPTY : String.valueOf(subnet.getValue());
698     }
699     public static <T> List<T> emptyIfNull(List<T> list) {
700         return (list == null) ? Collections.emptyList() : list;
701     }
702     public static <T> boolean isEmpty(Collection<T> collection) {
703         return (collection == null || collection.isEmpty()) ? true : false;
704     }
705     public static <T> boolean isNotEmpty(Collection<T> collection) {
706         return !isEmpty(collection);
707     }
708     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) {
709         HwVtep hwVtep = new HwVtep();
710         hwVtep.setGatewayIP(gatewayIP);
711         hwVtep.setHwIp(ipAddress);
712         hwVtep.setIpPrefix(ipPrefix);
713         hwVtep.setNode_id(node_id);
714         hwVtep.setTopo_id(topo_id);
715         hwVtep.setTransportZone(transportZone.getZoneName());
716         hwVtep.setTunnel_type(tunnel_type);
717         hwVtep.setVlanID(vlanID);
718         return hwVtep;
719     }
720
721     public static String getHwParentIf(String topo_id, String srcNodeid) {
722         return String.format("%s:%s", topo_id, srcNodeid);
723     }
724
725     public static <T extends DataObject> void syncWrite(LogicalDatastoreType datastoreType,
726                                                         InstanceIdentifier<T> path, T data, DataBroker broker) {
727         WriteTransaction tx = broker.newWriteOnlyTransaction();
728         tx.put(datastoreType, path, data, true);
729         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
730         try {
731             futures.get();
732         } catch (InterruptedException | ExecutionException e) {
733             LOG.error("ITMUtils:SyncWrite , Error writing to datastore (path, data) : ({}, {})", path, data);
734             throw new RuntimeException(e.getMessage());
735         }
736     }
737
738     public static List<BigInteger> getDpnIdList( List<DpnIds> dpnIds ) {
739         List<BigInteger> dpnList = new ArrayList<>() ;
740         for( DpnIds dpn : dpnIds) {
741             dpnList.add(dpn.getDPN()) ;
742         }
743         return dpnList ;
744     }
745
746     public static List<DpnIds> getDpnIdsListFromBigInt( List<BigInteger> dpnIds) {
747         List<DpnIds> dpnIdList = new ArrayList<>() ;
748         DpnIdsBuilder builder = new DpnIdsBuilder() ;
749         for( BigInteger dpnId : dpnIds) {
750             dpnIdList.add(builder.setKey(new DpnIdsKey(dpnId)).setDPN(dpnId).build() );
751         }
752         return dpnIdList;
753     }
754
755     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
756         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder =
757                 InstanceIdentifier.builder(InterfacesState.class)
758                         .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.class,
759                                 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
760                                         interfaceName));
761         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> id = idBuilder.build();
762         return id;
763     }
764     public static Boolean readMonitoringStateFromCache(DataBroker dataBroker) {
765         InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
766         TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
767         if(tunnelMonitorParams!=null)
768             return tunnelMonitorParams.isEnabled();
769         else
770             return ITMConstants.DEFAULT_MONITOR_ENABLED;
771     }
772
773     public static Integer readMonitorIntervalfromCache(DataBroker dataBroker) {
774         InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.create(TunnelMonitorInterval.class);
775         TunnelMonitorInterval tunnelMonitorIOptional = (TunnelMonitorInterval)DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"Interval",dataBroker,true);
776         if(tunnelMonitorIOptional!=null)
777             return tunnelMonitorIOptional.getInterval();
778         return null;
779
780     }
781
782     public static Integer determineMonitorInterval(DataBroker dataBroker) {
783         Integer monitorInterval = ItmUtils.readMonitorIntervalfromCache(dataBroker);
784         LOG.debug("determineMonitorInterval: monitorInterval from DS = {}", monitorInterval);
785         if(monitorInterval==null){
786             Class<? extends TunnelMonitoringTypeBase> monitorProtocol = determineMonitorProtocol(dataBroker);
787             if(monitorProtocol.isAssignableFrom(TunnelMonitoringTypeBfd.class))
788                 monitorInterval = ITMConstants.BFD_DEFAULT_MONITOR_INTERVAL;
789             else
790                 monitorInterval = ITMConstants.DEFAULT_MONITOR_INTERVAL;
791         }
792         LOG.debug("determineMonitorInterval: monitorInterval = {}", monitorInterval);
793         InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.builder(TunnelMonitorInterval.class).build();
794         TunnelMonitorInterval intervalBuilder = new TunnelMonitorIntervalBuilder().setInterval(monitorInterval).build();
795         ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, intervalBuilder, dataBroker, ItmUtils.DEFAULT_CALLBACK);
796         return monitorInterval;
797     }
798
799     public static List<String> getTunnelsofTzone(List<HwVtep> hwVteps, String tzone, DataBroker dataBroker, Boolean hwVtepsExist) {
800
801         List<String> tunnels = new ArrayList<>();
802         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
803                 child(TransportZone.class, new TransportZoneKey(tzone)).build();
804         Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
805         Class<? extends TunnelTypeBase> tunType = tZoneOptional.get().getTunnelType();
806         if (tZoneOptional.isPresent()) {
807             if (tZoneOptional.get().getSubnets() != null && !tZoneOptional.get().getSubnets().isEmpty()) {
808                 for (Subnets sub : tZoneOptional.get().getSubnets()) {
809                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
810                         for (Vteps vtepLocal : sub.getVteps()) {
811                             for (Vteps vtepRemote : sub.getVteps()) {
812                                 if (!vtepLocal.equals(vtepRemote)) {
813                                     InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(), tunType);
814                                     InstanceIdentifier<InternalTunnel> intIID =
815                                             InstanceIdentifier.builder(TunnelList.class).
816                                                     child(InternalTunnel.class, key).build();
817                                     Optional<InternalTunnel> TunnelsOptional =
818                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
819                                     if (TunnelsOptional.isPresent()) {
820                                         LOG.trace("Internal Tunnel added {}",TunnelsOptional.get().getTunnelInterfaceName());
821                                         tunnels.add(TunnelsOptional.get().getTunnelInterfaceName());
822                                     }
823                                 }
824                             }
825                             if(hwVteps!= null && !hwVteps.isEmpty()) {
826                                 for (HwVtep hwVtep : hwVteps) {
827                                     tunnels.add(getExtTunnel(hwVtep.getNode_id(), vtepLocal.getDpnId().toString(),
828                                             tunType, dataBroker));
829                                     tunnels.add(getExtTunnel(vtepLocal.getDpnId().toString(), hwVtep.getNode_id(),
830                                             tunType, dataBroker));
831                                 }
832                             }
833                         }
834                     }
835                 }
836             }
837         }
838         if (hwVtepsExist) {
839             for (HwVtep hwVtep : hwVteps) {
840                 for (HwVtep hwVtepOther : hwVteps) {
841                     if (!hwVtep.getHwIp().equals(hwVtepOther.getHwIp())) {
842                         tunnels.add(getExtTunnel(hwVtep.getNode_id(), hwVtepOther.getNode_id(), tunType, dataBroker));
843                         tunnels.add(getExtTunnel(hwVtepOther.getNode_id(), hwVtep.getNode_id(), tunType, dataBroker));
844                     }
845                 }
846             }
847         }
848         return tunnels;
849     }
850
851     public static List<String> getInternalTunnelsofTzone(String tzone, DataBroker dataBroker) {
852         List<String> tunnels = new ArrayList<>();
853         LOG.trace("Getting internal tunnels of {}",tzone);
854         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
855                 child(TransportZone.class, new TransportZoneKey(tzone)).build();
856         Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
857         if (tZoneOptional.isPresent()) {
858             if (tZoneOptional.get().getSubnets() != null && !tZoneOptional.get().getSubnets().isEmpty()) {
859                 for (Subnets sub : tZoneOptional.get().getSubnets()) {
860                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
861                         for (Vteps vtepLocal : sub.getVteps()) {
862                             for (Vteps vtepRemote : sub.getVteps()) {
863                                 if (!vtepLocal.equals(vtepRemote)) {
864                                     InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(), tZoneOptional.get().getTunnelType());
865                                     InstanceIdentifier<InternalTunnel> intIID =
866                                             InstanceIdentifier.builder(TunnelList.class).
867                                                     child(InternalTunnel.class, key).build();
868                                     Optional<InternalTunnel> TunnelsOptional =
869                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
870                                     if (TunnelsOptional.isPresent()) {
871                                         LOG.trace("Internal Tunnel added {}",
872                                                 TunnelsOptional.get().getTunnelInterfaceName());
873                                         tunnels.add(TunnelsOptional.get().getTunnelInterfaceName());
874                                     }
875                                 }
876                             }
877                         }
878                     }
879                 }
880             }
881         }
882         return tunnels;
883     }
884
885     private static String getExtTunnel(String node_id, String dpId,Class<? extends TunnelTypeBase> tunType, DataBroker dataBroker) {
886         LOG.trace("getting ext tunnel for {} and dpId {}",node_id,dpId);
887         ExternalTunnelKey key = getExternalTunnelKey(dpId, node_id, tunType);
888         InstanceIdentifier<ExternalTunnel> intIID = InstanceIdentifier.builder(ExternalTunnelList.class).
889                 child(ExternalTunnel.class, key).build();
890         Optional<ExternalTunnel> TunnelsOptional =
891                 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
892         if (TunnelsOptional.isPresent()) {
893             LOG.trace("ext tunnel returned {} ",TunnelsOptional.get().getTunnelInterfaceName());
894             return TunnelsOptional.get().getTunnelInterfaceName();
895         }
896         return null;
897     }
898     public static ExternalTunnelKey getExternalTunnelKey(String dst , String src, Class<? extends TunnelTypeBase> tunType) {
899         if (src.indexOf("physicalswitch") > 0) {
900             src = src.substring(0, src.indexOf("physicalswitch") - 1);
901         }
902         if (dst.indexOf("physicalswitch") > 0) {
903             dst = dst.substring(0, dst.indexOf("physicalswitch") - 1);
904         }
905         return new ExternalTunnelKey(dst, src, tunType);
906     }
907
908     public static List<TunnelEndPoints> getTEPsForDpn( BigInteger srcDpn, List<DPNTEPsInfo> dpnList) {
909         for (DPNTEPsInfo dpn : dpnList) {
910             if( dpn.getDPNID().equals(srcDpn)) {
911                 return dpn.getTunnelEndPoints() ;
912             }
913         }
914         return null ;
915     }
916     public static TunnelList getAllInternalTunnels(DataBroker broker) {
917         InstanceIdentifier<TunnelList> tunnelListInstanceIdentifier = InstanceIdentifier.builder(TunnelList.class).build();
918         Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, tunnelListInstanceIdentifier, broker);
919         if (tunnelList.isPresent()) {
920             return tunnelList.get();
921         }
922         return null;
923     }
924     public static InternalTunnel getInternalTunnel(String interfaceName, DataBroker broker) {
925         InternalTunnel internalTunnel = null;
926         TunnelList tunnelList = getAllInternalTunnels(broker);
927         if (tunnelList != null && tunnelList.getInternalTunnel() != null) {
928             List<InternalTunnel> internalTunnels = tunnelList.getInternalTunnel();
929             for (InternalTunnel tunnel : internalTunnels) {
930                 if (tunnel.getTunnelInterfaceName().equalsIgnoreCase(interfaceName)) {
931                     internalTunnel = tunnel;
932                     break;
933                 }
934             }
935         }
936         return internalTunnel;
937     }
938     public static ExternalTunnel getExternalTunnel(String interfaceName, DataBroker broker) {
939         ExternalTunnel externalTunnel = null;
940         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker);
941         for (ExternalTunnel tunnel : externalTunnels) {
942             if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
943                 externalTunnel = tunnel;
944                 break;
945             }
946         }
947         return externalTunnel;
948     }
949     public static List<ExternalTunnel> getAllExternalTunnels(DataBroker broker) {
950         List<ExternalTunnel> result = null;
951         InstanceIdentifier<ExternalTunnelList> id = InstanceIdentifier.builder(ExternalTunnelList.class).build();
952         Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, id, broker);
953         if (tunnelList.isPresent()) {
954             result = tunnelList.get().getExternalTunnel();
955         }
956         if (result == null) {
957             result = Collections.emptyList();
958         }
959         return result;
960     }
961     public static String convertTunnelTypetoString(Class<? extends TunnelTypeBase> tunType ) {
962         String tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
963         if( tunType.equals(TunnelTypeVxlan.class))
964             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN ;
965         else if( tunType.equals(TunnelTypeGre.class) )
966             tunnelType = ITMConstants.TUNNEL_TYPE_GRE ;
967         else if (tunnelType.equals(TunnelTypeMplsOverGre.class))
968             tunnelType = ITMConstants.TUNNEL_TYPE_MPLSoGRE;
969         return tunnelType ;
970     }
971
972
973     public static boolean isItmIfType(Class<? extends InterfaceType> ifType) {
974         if( (ifType != null) && (ifType.isAssignableFrom(Tunnel.class)) ) {
975             return true;
976         }
977         return false;
978     }
979
980     public static StateTunnelListKey getTunnelStateKey( org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface iface) {
981         StateTunnelListKey key = null;
982         if(isItmIfType(iface.getType())) {
983             key = new StateTunnelListKey(iface.getName());
984         }
985         return key;
986     }
987
988     public static void updateTunnelsCache(DataBroker broker) {
989         List<InternalTunnel> internalTunnels = getAllInternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
990         for (InternalTunnel tunnel : internalTunnels) {
991             itmCache.addInternalTunnel(tunnel);
992         }
993         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
994         for (ExternalTunnel tunnel : externalTunnels) {
995             itmCache.addExternalTunnel(tunnel);
996         }
997     }
998
999     public static List<ExternalTunnel> getAllExternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
1000         List<ExternalTunnel> result = null;
1001         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1002         Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1003         if (tunnelList.isPresent()) {
1004             result = tunnelList.get().getExternalTunnel();
1005         }
1006         if (result == null) {
1007             result = Collections.emptyList();
1008         }
1009         return result;
1010     }
1011
1012     public static List<InternalTunnel> getAllInternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
1013         List<InternalTunnel> result = null;
1014         InstanceIdentifier<TunnelList> iid = InstanceIdentifier.builder(TunnelList.class).build();
1015         Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1016         if (tunnelList.isPresent()) {
1017             result = tunnelList.get().getInternalTunnel();
1018         }
1019         if (result == null) {
1020             result = Collections.emptyList();
1021         }
1022         return result;
1023     }
1024
1025     public static Interface getInterface(
1026             String name, DataBroker broker) {
1027         Interface result = itmCache.getInterface(name);
1028         if (result == null) {
1029             InstanceIdentifier<Interface> iid =
1030                     InstanceIdentifier.builder(Interfaces.class)
1031                             .child(Interface.class, new InterfaceKey(name)).build();
1032             Optional<Interface> optInterface = read(LogicalDatastoreType.CONFIGURATION, iid, broker);
1033             if (optInterface.isPresent()) {
1034                 result = optInterface.get();
1035                 itmCache.addInterface(result);
1036             }
1037         }
1038         return result;
1039     }
1040
1041     public static Class<? extends TunnelMonitoringTypeBase> readMonitoringProtocolFromCache(DataBroker dataBroker) {
1042         InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
1043         TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
1044         if(tunnelMonitorParams!=null)
1045             return tunnelMonitorParams.getMonitorProtocol();
1046         return null;
1047     }
1048
1049     public static Class<? extends TunnelMonitoringTypeBase> determineMonitorProtocol(DataBroker dataBroker) {
1050         Class<? extends TunnelMonitoringTypeBase> monitoringProtocol = ItmUtils.readMonitoringProtocolFromCache(dataBroker);
1051         LOG.debug("determineMonitorProtocol: monitorProtocol from DS = {}", monitoringProtocol);
1052         if(monitoringProtocol==null)
1053             monitoringProtocol = ITMConstants.DEFAULT_MONITOR_PROTOCOL;
1054         LOG.debug("determineMonitorProtocol: monitorProtocol = {}", monitoringProtocol);
1055         Boolean monitorState = ItmUtils.readMonitoringStateFromCache(dataBroker);
1056         if(monitorState==null)
1057             monitorState = true;
1058         LOG.debug("determineMonitorProtocol: monitorState = {}", monitorState);
1059         InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.builder(TunnelMonitorParams.class).build();
1060         TunnelMonitorParams protocolBuilder = new TunnelMonitorParamsBuilder().setEnabled(monitorState).setMonitorProtocol(monitoringProtocol).build();
1061         ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, protocolBuilder, dataBroker, ItmUtils.DEFAULT_CALLBACK);
1062         return monitoringProtocol;
1063     }
1064
1065     public static List<DcGatewayIp> getDcGatewayIpList(DataBroker broker){
1066         InstanceIdentifier<DcGatewayIpList> dcGatewayIpListid = InstanceIdentifier.builder(DcGatewayIpList.class).build();
1067         Optional<DcGatewayIpList> dcGatewayIpListConfig = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, dcGatewayIpListid, broker);
1068         if(dcGatewayIpListConfig.isPresent()){
1069             DcGatewayIpList containerList = dcGatewayIpListConfig.get();
1070             if(containerList != null){
1071                 return (containerList.getDcGatewayIp());
1072             }
1073         }
1074         return null;
1075     }
1076 }