Merge "Cleanup and correct two small equals bugs"
[genius.git] / itm / itm-impl / src / main / java / org / opendaylight / genius / itm / impl / ItmUtils.java
1 /*
2  * Copyright © 2016, 2017 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.collect.ImmutableMap;
13 import com.google.common.net.InetAddresses;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import java.math.BigInteger;
18 import java.net.InetAddress;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.List;
23 import java.util.UUID;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.Future;
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.commons.net.util.SubnetUtils;
28 import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
29 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
30 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
31 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
32 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
33 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
34 import org.opendaylight.genius.interfacemanager.globals.IfmConstants;
35 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
36 import org.opendaylight.genius.itm.api.IITMProvider;
37 import org.opendaylight.genius.itm.confighelpers.HwVtep;
38 import org.opendaylight.genius.itm.globals.ITMConstants;
39 import org.opendaylight.genius.mdsalutil.ActionInfo;
40 import org.opendaylight.genius.mdsalutil.FlowEntity;
41 import org.opendaylight.genius.mdsalutil.InstructionInfo;
42 import org.opendaylight.genius.mdsalutil.MDSALUtil;
43 import org.opendaylight.genius.mdsalutil.MatchInfo;
44 import org.opendaylight.genius.mdsalutil.NwConstants;
45 import org.opendaylight.genius.mdsalutil.actions.ActionPuntToController;
46 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
47 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
48 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
49 import org.opendaylight.genius.utils.cache.DataStoreCache;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.Tunnel;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.*;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.*;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifier;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierKey;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.*;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchema;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaKey;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIds;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsKey;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPool;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPoolKey;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpoints;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpointsBuilder;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelList;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelOperStatus;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeBase;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeInternal;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeExternal;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeHwvtep;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelsState;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfo;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoKey;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPoints;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsKey;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.tunnel.end.points.TzMembership;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.tunnel.end.points.TzMembershipBuilder;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnel;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelBuilder;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelKey;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.StateTunnelList;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.StateTunnelListBuilder;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.StateTunnelListKey;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.state.tunnel.list.DstInfoBuilder;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.state.tunnel.list.SrcInfoBuilder;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.DcGatewayIpList;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.TransportZones;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.dc.gateway.ip.list.DcGatewayIp;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TepsNotHostedInTransportZone;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TepsNotHostedInTransportZoneKey;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZone;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZoneKey;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.Subnets;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.subnets.Vteps;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
113 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
114 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
115 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
116 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
117 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
118 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
119 import org.opendaylight.yangtools.yang.binding.DataObject;
120 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
121 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
122 import org.opendaylight.yangtools.yang.common.RpcResult;
123 import org.slf4j.Logger;
124 import org.slf4j.LoggerFactory;
125
126 public class ItmUtils {
127
128     public static final String DUMMY_IP_ADDRESS = "0.0.0.0";
129     public static final String TUNNEL_TYPE_VXLAN = "VXLAN";
130     public static final String TUNNEL_TYPE_GRE = "GRE";
131     public static final String TUNNEL = "tun";
132     public static final IpPrefix DUMMY_IP_PREFIX = new IpPrefix(
133         ITMConstants.DUMMY_PREFIX.toCharArray());
134     public static ItmCache itmCache = new ItmCache();
135
136     private static final Logger LOG = LoggerFactory.getLogger(ItmUtils.class);
137
138     public static final ImmutableMap<String, Class<? extends TunnelTypeBase>>
139         TUNNEL_TYPE_MAP =
140         new ImmutableMap.Builder<String, Class<? extends TunnelTypeBase>>()
141             .put(ITMConstants.TUNNEL_TYPE_GRE, TunnelTypeGre.class)
142             .put(ITMConstants.TUNNEL_TYPE_MPLSoGRE, TunnelTypeMplsOverGre.class)
143             .put(ITMConstants.TUNNEL_TYPE_VXLAN, TunnelTypeVxlan.class)
144             .build();
145
146     public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
147         @Override
148         public void onSuccess(Void result) {
149             LOG.debug("Success in Datastore write operation");
150         }
151
152         @Override
153         public void onFailure(Throwable error) {
154             LOG.error("Error in Datastore write operation", error);
155         }
156     };
157
158     public static <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
159                                                           InstanceIdentifier<T> path, DataBroker broker) {
160         try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
161             return tx.read(datastoreType, path).get();
162         } catch (Exception e) {
163             throw new RuntimeException(e);
164         }
165     }
166
167     public static <T extends DataObject> void asyncWrite(LogicalDatastoreType datastoreType,
168                                                          InstanceIdentifier<T> path, T data, DataBroker broker, FutureCallback<Void> callback) {
169         WriteTransaction tx = broker.newWriteOnlyTransaction();
170         tx.put(datastoreType, path, data, true);
171         Futures.addCallback(tx.submit(), callback);
172     }
173
174     public static <T extends DataObject> void asyncUpdate(LogicalDatastoreType datastoreType,
175                                                           InstanceIdentifier<T> path, T data, DataBroker broker, FutureCallback<Void> callback) {
176         WriteTransaction tx = broker.newWriteOnlyTransaction();
177         tx.merge(datastoreType, path, data, true);
178         Futures.addCallback(tx.submit(), callback);
179     }
180
181     public static <T extends DataObject> void asyncDelete(LogicalDatastoreType datastoreType,
182                                                           InstanceIdentifier<T> path, DataBroker broker, FutureCallback<Void> callback) {
183         WriteTransaction tx = broker.newWriteOnlyTransaction();
184         tx.delete(datastoreType, path);
185         Futures.addCallback(tx.submit(), callback);
186     }
187     public static <T extends DataObject> void asyncBulkRemove(final DataBroker broker,final LogicalDatastoreType datastoreType,
188                                                               List<InstanceIdentifier<T>> pathList, FutureCallback<Void> callback) {
189         if (!pathList.isEmpty()) {
190             WriteTransaction tx = broker.newWriteOnlyTransaction();
191             for (InstanceIdentifier<T> path : pathList) {
192                 tx.delete(datastoreType, path);
193             }
194             Futures.addCallback(tx.submit(), callback);
195         }
196     }
197
198     public static String getInterfaceName(final BigInteger datapathid, final String portName, final Integer vlanId) {
199         return String.format("%s:%s:%s", datapathid, portName, vlanId);
200     }
201
202     public static BigInteger getDpnIdFromInterfaceName(String interfaceName) {
203         String[] dpnStr = interfaceName.split(":");
204         BigInteger dpnId = new BigInteger(dpnStr[0]);
205         return dpnId;
206     }
207
208     public static String getTrunkInterfaceName(IdManagerService idManager, String parentInterfaceName,
209                                                String localHostName, String remoteHostName, String tunnelType) {
210         String tunnelTypeStr;
211         if(tunnelType.contains("TunnelTypeGre")) {
212             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_GRE;
213         } else {
214             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_VXLAN;
215         }
216         String trunkInterfaceName = String.format(  "%s:%s:%s:%s", parentInterfaceName, localHostName,
217                 remoteHostName, tunnelTypeStr);
218         LOG.trace("trunk interface name is {}", trunkInterfaceName);
219         trunkInterfaceName = String.format("%s%s", TUNNEL, getUniqueIdString(trunkInterfaceName));
220         return trunkInterfaceName;
221     }
222
223     public static void releaseIdForTrunkInterfaceName(IdManagerService idManager, String parentInterfaceName, String localHostName, String remoteHostName, String tunnelType) {
224         String tunnelTypeStr;
225         if(tunnelType.contains("TunnelTypeGre")) {
226             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_GRE;
227         } else {
228             tunnelTypeStr = ITMConstants.TUNNEL_TYPE_VXLAN;
229         }
230         String trunkInterfaceName = String.format("%s:%s:%s:%s", parentInterfaceName, localHostName, remoteHostName, tunnelTypeStr);
231         LOG.trace("Releasing Id for trunkInterface - {}", trunkInterfaceName );
232         //releaseId(idManager, trunkInterfaceName) ;
233     }
234
235     public static InetAddress getInetAddressFromIpAddress(IpAddress ip) {
236         return InetAddresses.forString(ip.getIpv4Address().getValue());
237     }
238
239     public static InstanceIdentifier<DPNTEPsInfo> getDPNTEPInstance(BigInteger dpIdKey) {
240         InstanceIdentifier.InstanceIdentifierBuilder<DPNTEPsInfo> dpnTepInfoBuilder =
241                 InstanceIdentifier.builder(DpnEndpoints.class).child(DPNTEPsInfo.class,
242                         new DPNTEPsInfoKey(dpIdKey));
243         InstanceIdentifier<DPNTEPsInfo> dpnInfo = dpnTepInfoBuilder.build();
244         return dpnInfo;
245     }
246
247     public static DPNTEPsInfo createDPNTepInfo(BigInteger dpId, List<TunnelEndPoints> endpoints) {
248
249         return new DPNTEPsInfoBuilder().setKey(new DPNTEPsInfoKey(dpId)).setTunnelEndPoints(endpoints).build();
250     }
251
252     public static TunnelEndPoints createTunnelEndPoints(BigInteger dpnId, IpAddress ipAddress, String portName,
253                                                         boolean isOfTunnel, int vlanId, IpPrefix prefix,
254                                                         IpAddress gwAddress, List<TzMembership> zones,
255                                                         Class<? extends TunnelTypeBase>  tunnel_type) {
256         // when Interface Mgr provides support to take in Dpn Id
257         return new TunnelEndPointsBuilder().setKey(new TunnelEndPointsKey(ipAddress, portName,tunnel_type, vlanId))
258                 .setSubnetMask(prefix).setGwIpAddress(gwAddress).setTzMembership(zones)
259                 .setOptionOfTunnel(isOfTunnel).setInterfaceName(ItmUtils.getInterfaceName(dpnId, portName, vlanId))
260                 .setTunnelType(tunnel_type).build();
261     }
262
263     public static DpnEndpoints createDpnEndpoints(List<DPNTEPsInfo> dpnTepInfo) {
264         return new DpnEndpointsBuilder().setDPNTEPsInfo(dpnTepInfo).build();
265     }
266
267     public static InstanceIdentifier<Interface> buildId(String interfaceName) {
268         InstanceIdentifierBuilder<Interface> idBuilder =
269                 InstanceIdentifier.builder(Interfaces.class).child(Interface.class, new InterfaceKey(interfaceName));
270         InstanceIdentifier<Interface> id = idBuilder.build();
271         return id;
272     }
273
274     public static Interface buildTunnelInterface(BigInteger dpn, String ifName, String desc, boolean enabled,
275                                                  Class<? extends TunnelTypeBase> tunType, IpAddress localIp,
276                                                  IpAddress remoteIp, IpAddress gatewayIp, Integer vlanId,
277                                                  boolean internal, Boolean monitorEnabled,
278                                                  Class<? extends TunnelMonitoringTypeBase> monitorProtocol,
279                                                  Integer monitorInterval, boolean useOfTunnel) {
280         InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(ifName)).setName(ifName)
281                 .setDescription(desc).setEnabled(enabled).setType(Tunnel.class);
282         ParentRefs parentRefs = new ParentRefsBuilder().setDatapathNodeIdentifier(dpn).build();
283         builder.addAugmentation(ParentRefs.class, parentRefs);
284         Long monitoringInterval=null;
285         if( vlanId > 0) {
286             IfL2vlan l2vlan = new IfL2vlanBuilder().setVlanId(new VlanId(vlanId)).build();
287             builder.addAugmentation(IfL2vlan.class, l2vlan);
288         }
289         LOG.debug("buildTunnelInterface: monitorProtocol = {} and monitorInterval = {}",monitorProtocol.getName(),monitorInterval);
290
291
292         if(monitorInterval != null) {
293             monitoringInterval = monitorInterval.longValue();
294         }
295
296         IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(remoteIp).setTunnelGateway(gatewayIp)
297                 .setTunnelSource(localIp).setTunnelInterfaceType(tunType).setInternal(internal)
298                 .setMonitorEnabled(monitorEnabled).setMonitorProtocol(monitorProtocol)
299                 .setMonitorInterval(monitoringInterval).setTunnelRemoteIpFlow(useOfTunnel)
300                 .build();
301         builder.addAugmentation(IfTunnel.class, tunnel);
302         return builder.build();
303     }
304
305     public static Interface buildHwTunnelInterface(String tunnelIfName, String desc, boolean enabled, String topo_id,
306                                                    String node_id, Class<? extends TunnelTypeBase> tunType, IpAddress srcIp, IpAddress destIp,
307                                                    IpAddress gWIp, Boolean monitor_enabled, Class<? extends TunnelMonitoringTypeBase> monitorProtocol, Integer monitor_interval){
308         InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(tunnelIfName)).setName(
309                 tunnelIfName).setDescription(desc).
310                 setEnabled(enabled).setType(Tunnel.class);
311         List<NodeIdentifier> nodeIds = new ArrayList<>();
312         NodeIdentifier hWnode = new NodeIdentifierBuilder().setKey(new NodeIdentifierKey(topo_id)).setTopologyId(
313                 topo_id).
314                 setNodeId(node_id).build();
315         nodeIds.add(hWnode);
316         ParentRefs parent = new ParentRefsBuilder().setNodeIdentifier(nodeIds).build();
317         builder.addAugmentation(ParentRefs.class, parent);
318         Long monitoringInterval = (long) ITMConstants.DEFAULT_MONITOR_INTERVAL;
319         Boolean monitoringEnabled = true;
320         Class<? extends TunnelMonitoringTypeBase> monitoringProtocol = ITMConstants.DEFAULT_MONITOR_PROTOCOL;
321         if(monitor_interval!= null) {
322             monitoringInterval = monitor_interval.longValue();
323         }
324         if(monitor_enabled!=null  ) {
325             monitoringEnabled = monitor_enabled;
326         }
327         if(monitorProtocol!=null) {
328             monitoringProtocol = monitorProtocol;
329         }
330         IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(destIp).setTunnelGateway(gWIp).setTunnelSource(
331                 srcIp).setMonitorEnabled(monitoringEnabled).setMonitorProtocol(monitorProtocol).setMonitorInterval(100L).
332                 setTunnelInterfaceType(tunType).setInternal(false).build();
333         builder.addAugmentation(IfTunnel.class, tunnel);
334         LOG.trace("iftunnel {} built from hwvtep {} ", tunnel, node_id);
335         return builder.build();
336     }
337
338
339     public static InternalTunnel buildInternalTunnel( BigInteger srcDpnId, BigInteger dstDpnId,
340                                                       Class<? extends TunnelTypeBase> tunType,
341                                                       String trunkInterfaceName) {
342         InternalTunnel tnl = new InternalTunnelBuilder().setKey(new InternalTunnelKey(dstDpnId, srcDpnId, tunType)).setDestinationDPN(dstDpnId)
343                 .setSourceDPN(srcDpnId).setTransportType(tunType)
344                 .setTunnelInterfaceNames(Collections.singletonList(trunkInterfaceName)).build();
345         return tnl ;
346     }
347
348     public static ExternalTunnel buildExternalTunnel(String srcNode, String dstNode,
349                                                      Class<? extends TunnelTypeBase> tunType,
350                                                      String trunkInterfaceName) {
351         ExternalTunnel extTnl = new ExternalTunnelBuilder().setKey(
352                 new ExternalTunnelKey(dstNode, srcNode, tunType))
353                 .setSourceDevice(srcNode).setDestinationDevice(dstNode)
354                 .setTunnelInterfaceName(trunkInterfaceName)
355                 .setTransportType(tunType).build();
356         return extTnl ;
357     }
358
359     public static List<DPNTEPsInfo> getTunnelMeshInfo(DataBroker dataBroker) {
360         List<DPNTEPsInfo> dpnTEPs= null ;
361
362         // Read the Mesh Information from Cache if not read from the DS
363         dpnTEPs = getTunnelMeshInfo() ;
364         if( dpnTEPs != null ) {
365             return dpnTEPs ;
366         }
367
368         // Read the EndPoint Info from the operational database
369         InstanceIdentifierBuilder<DpnEndpoints> depBuilder = InstanceIdentifier.builder( DpnEndpoints.class);
370         InstanceIdentifier<DpnEndpoints> deps = depBuilder.build();
371         Optional<DpnEndpoints> dpnEps = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, deps, dataBroker);
372         if (dpnEps.isPresent()) {
373             DpnEndpoints tn= dpnEps.get() ;
374             dpnTEPs = tn.getDPNTEPsInfo();
375             LOG.debug( "Read from CONFIGURATION datastore - No. of Dpns " , dpnTEPs.size() );
376         } else {
377             LOG.debug( "No Dpn information in CONFIGURATION datastore "  );
378         }
379         return dpnTEPs ;
380     }
381
382     // Reading the Mesh Information from Cache
383     public static List<DPNTEPsInfo> getTunnelMeshInfo(){
384         List<DPNTEPsInfo> dpnTepsInfo = null ;
385         List<Object> values = null ;
386
387         values = DataStoreCache.getValues(ITMConstants.DPN_TEPs_Info_CACHE_NAME);
388         if( values != null ) {
389             dpnTepsInfo = new ArrayList<>() ;
390             for( Object value : values ) {
391                 dpnTepsInfo.add((DPNTEPsInfo)value) ;
392             }
393         }
394         return dpnTepsInfo ;
395     }
396
397     public static int getUniqueId(IdManagerService idManager, String idKey) {
398         AllocateIdInput getIdInput = new AllocateIdInputBuilder()
399                 .setPoolName(ITMConstants.ITM_IDPOOL_NAME)
400                 .setIdKey(idKey).build();
401
402         try {
403             Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
404             RpcResult<AllocateIdOutput> rpcResult = result.get();
405             if(rpcResult.isSuccessful()) {
406                 return rpcResult.getResult().getIdValue().intValue();
407             } else {
408                 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
409             }
410         } catch (InterruptedException | ExecutionException e) {
411             LOG.warn("Exception when getting Unique Id",e);
412         }
413         return 0;
414     }
415
416     public static String getUniqueIdString(String idKey) {
417         return UUID.nameUUIDFromBytes(idKey.getBytes()).toString().substring(0, 12).replace("-", "");
418     }
419
420     public static void releaseId(IdManagerService idManager, String idKey) {
421         ReleaseIdInput idInput =
422                 new ReleaseIdInputBuilder().setPoolName(ITMConstants.ITM_IDPOOL_NAME).setIdKey(idKey).build();
423         try {
424             Future<RpcResult<Void>> result = idManager.releaseId(idInput);
425             RpcResult<Void> rpcResult = result.get();
426             if(!rpcResult.isSuccessful()) {
427                 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
428             }
429         } catch (InterruptedException | ExecutionException e) {
430             LOG.warn("Exception when getting Unique Id for key {}", idKey, e);
431         }
432     }
433
434     public static List<DPNTEPsInfo> getDPNTEPListFromDPNId(DataBroker dataBroker, List<BigInteger> dpnIds) {
435         List<DPNTEPsInfo> meshedDpnList = getTunnelMeshInfo(dataBroker) ;
436         List<DPNTEPsInfo> cfgDpnList = new ArrayList<>();
437         if( null != meshedDpnList) {
438             for(BigInteger dpnId : dpnIds) {
439                 for( DPNTEPsInfo teps : meshedDpnList ) {
440                     if( dpnId.equals(teps.getDPNID())) {
441                         cfgDpnList.add( teps) ;
442                     }
443                 }
444             }
445         }
446         return cfgDpnList;
447     }
448
449     public static void setUpOrRemoveTerminatingServiceTable(BigInteger dpnId, IMdsalApiManager mdsalManager, boolean addFlag) {
450         String logmsg = addFlag ? "Installing" : "Removing";
451         LOG.trace( logmsg + " PUNT to Controller flow in DPN {} ", dpnId );
452         List<ActionInfo> listActionInfo = new ArrayList<>();
453         listActionInfo.add(new ActionPuntToController());
454
455         try {
456             List<MatchInfo> mkMatches = new ArrayList<>();
457
458             mkMatches.add(new MatchTunnelId(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)));
459
460             List<InstructionInfo> mkInstructions = new ArrayList<>();
461             mkInstructions.add(new InstructionApplyActions(listActionInfo));
462
463             FlowEntity terminatingServiceTableFlowEntity = MDSALUtil
464                     .buildFlowEntity(
465                             dpnId,
466                             NwConstants.INTERNAL_TUNNEL_TABLE,
467                             getFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE,
468                                     ITMConstants.LLDP_SERVICE_ID), 5, String.format("%s:%d","ITM Flow Entry ",ITMConstants.LLDP_SERVICE_ID),
469                             0, 0, ITMConstants.COOKIE_ITM
470                                     .add(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)),
471                             mkMatches, mkInstructions);
472             if(addFlag) {
473                 mdsalManager.installFlow(terminatingServiceTableFlowEntity);
474             } else {
475                 mdsalManager.removeFlow(terminatingServiceTableFlowEntity);
476             }
477         } catch (Exception e) {
478             LOG.error("Error while setting up Table 36 for {}", dpnId, e);
479         }
480     }
481
482     private static String getFlowRef(long termSvcTable, int svcId) {
483         return String.valueOf(termSvcTable) + svcId;
484     }
485     public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier(String schemaName) {
486         return InstanceIdentifier.builder(VtepConfigSchemas.class)
487                 .child(VtepConfigSchema.class, new VtepConfigSchemaKey(schemaName)).build();
488     }
489
490     public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier() {
491         return InstanceIdentifier.builder(VtepConfigSchemas.class).child(VtepConfigSchema.class).build();
492     }
493     public static InstanceIdentifier<VtepConfigSchemas> getVtepConfigSchemasIdentifier() {
494         return InstanceIdentifier.builder(VtepConfigSchemas.class).build();
495     }
496     public static InstanceIdentifier<VtepIpPool> getVtepIpPoolIdentifier(String subnetCidr) {
497         return InstanceIdentifier.builder(VtepIpPools.class).child(VtepIpPool.class, new VtepIpPoolKey(subnetCidr))
498                 .build();
499     }
500     public static VtepConfigSchema validateForAddVtepConfigSchema(VtepConfigSchema schema,
501                                                                   List<VtepConfigSchema> existingSchemas) {
502         VtepConfigSchema validSchema = validateVtepConfigSchema(schema);
503         for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
504             if (!StringUtils.equalsIgnoreCase(schema.getSchemaName(), existingSchema.getSchemaName())
505                     && schema.getSubnet().equals(existingSchema.getSubnet())) {
506                 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
507                 Preconditions.checkArgument(false, "VTEP schema with subnet [" + subnetCidr +
508                         "] already exists. Multiple VTEP schemas with same subnet is not allowed.");
509             }
510         }
511         if (isNotEmpty(getDpnIdList(validSchema.getDpnIds()))) {
512             String tzone = validSchema.getTransportZoneName();
513             List<BigInteger> lstDpns = getConflictingDpnsAlreadyConfiguredWithTz(validSchema.getSchemaName(), tzone,
514                     getDpnIdList(validSchema.getDpnIds()), existingSchemas);
515             if (!lstDpns.isEmpty()) {
516                 Preconditions.checkArgument(false,
517                         "DPN's " + lstDpns + " already configured for transport zone " +
518                                 tzone + ". Only one end point per transport Zone per Dpn is allowed.");
519             }
520             if (schema.getTunnelType().equals(TunnelTypeGre.class)){
521                 validateForSingleGreTep(validSchema.getSchemaName(), getDpnIdList(validSchema.getDpnIds()), existingSchemas);
522             }
523         }
524         return validSchema;
525     }
526     private static void validateForSingleGreTep(String schemaName, List<BigInteger> lstDpnsForAdd,
527                                                 List<VtepConfigSchema> existingSchemas) {
528         for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
529             if (TunnelTypeGre.class.equals(existingSchema.getTunnelType())
530                     && !StringUtils.equalsIgnoreCase(schemaName, existingSchema.getSchemaName())) {
531                 List<BigInteger> lstConflictingDpns = new ArrayList<>(getDpnIdList(existingSchema.getDpnIds()));
532                 lstConflictingDpns.retainAll(emptyIfNull(lstDpnsForAdd));
533                 if (!lstConflictingDpns.isEmpty()) {
534                     String errMsg = "DPN's " + lstConflictingDpns +
535                             " already configured with GRE TEP. Mutiple GRE TEP's on a single DPN are not allowed.";
536                     Preconditions.checkArgument(false, errMsg);
537                 }
538             }
539         }
540     }
541     public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
542         Preconditions.checkNotNull(schema);
543         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
544         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
545         Preconditions.checkArgument(schema.getVlanId() >= 0 && schema.getVlanId() < 4095,
546                 "Invalid VLAN ID, range (0-4094)");
547         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
548         Preconditions.checkNotNull(schema.getSubnet());
549         String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
550         SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
551         IpAddress gatewayIp = schema.getGatewayIp();
552         if (gatewayIp != null) {
553             String strGatewayIp = String.valueOf(gatewayIp.getValue());
554             if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS) && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
555                 Preconditions.checkArgument(false, "Gateway IP address " + strGatewayIp +
556                         " is not in subnet range " + subnetCidr);
557             }
558         }
559         ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
560         return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
561     }
562     public static String validateTunnelType(String tunnelType) {
563         if (tunnelType == null) {
564             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
565         } else {
566             tunnelType = StringUtils.upperCase(tunnelType);
567             String error = "Invalid tunnel type. Valid values: " +
568                     ITMConstants.TUNNEL_TYPE_VXLAN + " | " + ITMConstants.TUNNEL_TYPE_GRE;
569             Preconditions.checkArgument(ITMConstants.TUNNEL_TYPE_VXLAN.equals(tunnelType)
570                     || ITMConstants.TUNNEL_TYPE_GRE.equals(tunnelType), error);
571         }
572         return tunnelType;
573     }
574     private static List<BigInteger> getConflictingDpnsAlreadyConfiguredWithTz(String schemaName, String tzone,
575                                                                               List<BigInteger> lstDpns, List<VtepConfigSchema> existingSchemas) {
576         List<BigInteger> lstConflictingDpns = new ArrayList<>();
577         for (VtepConfigSchema schema : emptyIfNull(existingSchemas)) {
578             if (!StringUtils.equalsIgnoreCase(schemaName, schema.getSchemaName())
579                     && StringUtils.equals(schema.getTransportZoneName(), tzone)) {
580                 lstConflictingDpns = new ArrayList<>(getDpnIdList(schema.getDpnIds()));
581                 lstConflictingDpns.retainAll(lstDpns);
582                 if (!lstConflictingDpns.isEmpty()) {
583                     break;
584                 }
585             }
586         }
587         return lstConflictingDpns;
588     }
589     public static VtepConfigSchema constructVtepConfigSchema(String schemaName, String portName, Integer vlanId,
590                                                              String subnetMask, String gatewayIp, String transportZone,String tunnelType, List<BigInteger> dpnIds,
591                                                              String excludeIpFilter) {
592         IpAddress gatewayIpObj = StringUtils.isBlank(gatewayIp) ? null : new IpAddress(gatewayIp.toCharArray());
593         IpPrefix subnet = StringUtils.isBlank(subnetMask) ? null : new IpPrefix(subnetMask.toCharArray());
594         Class<? extends TunnelTypeBase> tunType ;
595         if( tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN)) {
596             tunType = TunnelTypeVxlan.class ;
597         } else {
598             tunType = TunnelTypeGre.class ;
599         }
600         VtepConfigSchemaBuilder schemaBuilder = new VtepConfigSchemaBuilder().setSchemaName(schemaName)
601                 .setPortName(portName).setVlanId(vlanId).setSubnet(subnet).setGatewayIp(gatewayIpObj)
602                 .setTransportZoneName(transportZone).setTunnelType(tunType).setDpnIds(getDpnIdsListFromBigInt(dpnIds))
603                 .setExcludeIpFilter(excludeIpFilter);
604         return schemaBuilder.build();
605     }
606     public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
607         final List<IpAddress> lstIpAddress = new ArrayList<>();
608         if (StringUtils.isBlank(excludeIpFilter)) {
609             return lstIpAddress;
610         }
611         final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
612         for (String ip : arrIps) {
613             if (StringUtils.countMatches(ip, "-") == 1) {
614                 final String[] arrIpRange = StringUtils.split(ip, '-');
615                 String strStartIp = StringUtils.trim(arrIpRange[0]);
616                 String strEndIp = StringUtils.trim(arrIpRange[1]);
617                 Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
618                         "Invalid exclude IP filter: invalid IP address value " + strStartIp);
619                 Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
620                         "Invalid exclude IP filter: invalid IP address value " + strEndIp);
621                 Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
622                         "Invalid exclude IP filter: IP address [" + strStartIp +
623                                 "] not in subnet range " + subnetInfo.getCidrSignature());
624                 Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
625                         "Invalid exclude IP filter: IP address [" + strEndIp +
626                                 "] not in subnet range " + subnetInfo.getCidrSignature());
627                 int startIp = subnetInfo.asInteger(strStartIp);
628                 int endIp = subnetInfo.asInteger(strEndIp);
629
630                 Preconditions.checkArgument(startIp < endIp,
631                         "Invalid exclude IP filter: Invalid range [" + ip + "] ");
632                 for (int i = startIp; i <= endIp; i++) {
633                     String ipAddress = ipFormat(toIpArray(i));
634                     validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
635                 }
636             } else {
637                 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
638             }
639         }
640         return lstIpAddress;
641     }
642     private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
643                                                       String ipAddress) {
644         String ip = StringUtils.trim(ipAddress);
645         Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
646                 "Invalid exclude IP filter: invalid IP address value " + ip);
647         Preconditions.checkArgument(subnetInfo.isInRange(ip),
648                 "Invalid exclude IP filter: IP address [" + ip + "] not in subnet range " +
649                         subnetInfo.getCidrSignature());
650         lstIpAddress.add(new IpAddress(ip.toCharArray()));
651     }
652     private static int[] toIpArray(int val) {
653         int[] ret = new int[4];
654         for (int j = 3; j >= 0; --j) {
655             ret[j] |= val >>> 8 * (3 - j) & 0xff;
656         }
657         return ret;
658     }
659     private static String ipFormat(int[] octets) {
660         StringBuilder str = new StringBuilder();
661         for (int i = 0; i < octets.length; ++i) {
662             str.append(octets[i]);
663             if (i != octets.length - 1) {
664                 str.append(".");
665             }
666         }
667         return str.toString();
668     }
669     public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd,
670                                                                List<BigInteger> lstDpnsForDelete, IITMProvider itmProvider) {
671         Preconditions.checkArgument(StringUtils.isNotBlank(schemaName));
672         if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty())
673                 && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) {
674             Preconditions.checkArgument(false,
675                     "DPN ID list for add | delete is null or empty in schema " + schemaName);
676         }
677         VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName);
678         if (schema == null) {
679             Preconditions.checkArgument(false, "Specified VTEP Schema [" + schemaName +
680                     "] doesn't exists!");
681         }
682         List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds());
683         if (isNotEmpty(lstDpnsForAdd)) {
684             //  if (isNotEmpty(existingDpnIds)) {
685             List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds);
686             lstAlreadyExistingDpns.retainAll(lstDpnsForAdd);
687             Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(),
688                     "DPN ID's " + lstAlreadyExistingDpns +
689                             " already exists in VTEP schema [" + schemaName + "]");
690             //    }
691             if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
692                 validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd, itmProvider.getAllVtepConfigSchemas());
693             }
694         }
695         if (isNotEmpty(lstDpnsForDelete)) {
696             if (existingDpnIds == null || existingDpnIds.isEmpty()) {
697                 String builder = "DPN ID's " + lstDpnsForDelete +
698                         " specified for delete from VTEP schema [" + schemaName +
699                         "] are not configured in the schema.";
700                 Preconditions.checkArgument(false, builder);
701             } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) {
702                 List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete);
703                 lstConflictingDpns.removeAll(existingDpnIds);
704                 String builder = "DPN ID's " + lstConflictingDpns +
705                         " specified for delete from VTEP schema [" + schemaName +
706                         "] are not configured in the schema.";
707                 Preconditions.checkArgument(false, builder);
708             }
709         }
710         return schema;
711     }
712     public static String getSubnetCidrAsString(IpPrefix subnet) {
713         return subnet == null ? StringUtils.EMPTY : String.valueOf(subnet.getValue());
714     }
715     public static <T> List<T> emptyIfNull(List<T> list) {
716         return list == null ? Collections.emptyList() : list;
717     }
718     public static <T> boolean isEmpty(Collection<T> collection) {
719         return collection == null || collection.isEmpty();
720     }
721     public static <T> boolean isNotEmpty(Collection<T> collection) {
722         return !isEmpty(collection);
723     }
724     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) {
725         HwVtep hwVtep = new HwVtep();
726         hwVtep.setGatewayIP(gatewayIP);
727         hwVtep.setHwIp(ipAddress);
728         hwVtep.setIpPrefix(ipPrefix);
729         hwVtep.setNode_id(node_id);
730         hwVtep.setTopo_id(topo_id);
731         hwVtep.setTransportZone(transportZone.getZoneName());
732         hwVtep.setTunnel_type(tunnel_type);
733         hwVtep.setVlanID(vlanID);
734         return hwVtep;
735     }
736
737     public static String getHwParentIf(String topo_id, String srcNodeid) {
738         return String.format("%s:%s", topo_id, srcNodeid);
739     }
740
741     public static <T extends DataObject> void syncWrite(LogicalDatastoreType datastoreType,
742                                                         InstanceIdentifier<T> path, T data, DataBroker broker) {
743         WriteTransaction tx = broker.newWriteOnlyTransaction();
744         tx.put(datastoreType, path, data, true);
745         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
746         try {
747             futures.get();
748         } catch (InterruptedException | ExecutionException e) {
749             LOG.error("ITMUtils:SyncWrite , Error writing to datastore (path, data) : ({}, {})", path, data);
750             throw new RuntimeException(e.getMessage());
751         }
752     }
753
754     public static List<BigInteger> getDpnIdList( List<DpnIds> dpnIds ) {
755         List<BigInteger> dpnList = new ArrayList<>() ;
756         for( DpnIds dpn : dpnIds) {
757             dpnList.add(dpn.getDPN()) ;
758         }
759         return dpnList ;
760     }
761
762     public static List<DpnIds> getDpnIdsListFromBigInt( List<BigInteger> dpnIds) {
763         List<DpnIds> dpnIdList = new ArrayList<>() ;
764         DpnIdsBuilder builder = new DpnIdsBuilder() ;
765         for( BigInteger dpnId : dpnIds) {
766             dpnIdList.add(builder.setKey(new DpnIdsKey(dpnId)).setDPN(dpnId).build() );
767         }
768         return dpnIdList;
769     }
770
771     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
772         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder =
773                 InstanceIdentifier.builder(InterfacesState.class)
774                         .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.class,
775                                 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
776                                         interfaceName));
777         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> id = idBuilder.build();
778         return id;
779     }
780     public static Boolean readMonitoringStateFromCache(DataBroker dataBroker) {
781         InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
782         TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
783         if(tunnelMonitorParams!=null) {
784             return tunnelMonitorParams.isEnabled();
785         } else {
786             return ITMConstants.DEFAULT_MONITOR_ENABLED;
787         }
788     }
789
790     public static Integer readMonitorIntervalfromCache(DataBroker dataBroker) {
791         InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.create(TunnelMonitorInterval.class);
792         TunnelMonitorInterval tunnelMonitorIOptional = (TunnelMonitorInterval)DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"Interval",dataBroker,true);
793         if(tunnelMonitorIOptional!=null) {
794             return tunnelMonitorIOptional.getInterval();
795         }
796         return null;
797
798     }
799
800     public static Integer determineMonitorInterval(DataBroker dataBroker) {
801         Integer monitorInterval = ItmUtils.readMonitorIntervalfromCache(dataBroker);
802         LOG.debug("determineMonitorInterval: monitorInterval from DS = {}", monitorInterval);
803         if(monitorInterval==null){
804             Class<? extends TunnelMonitoringTypeBase> monitorProtocol = determineMonitorProtocol(dataBroker);
805             if(monitorProtocol.isAssignableFrom(TunnelMonitoringTypeBfd.class)) {
806                 monitorInterval = ITMConstants.BFD_DEFAULT_MONITOR_INTERVAL;
807             } else {
808                 monitorInterval = ITMConstants.DEFAULT_MONITOR_INTERVAL;
809             }
810         }
811         LOG.debug("determineMonitorInterval: monitorInterval = {}", monitorInterval);
812         InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.builder(TunnelMonitorInterval.class).build();
813         TunnelMonitorInterval intervalBuilder = new TunnelMonitorIntervalBuilder().setInterval(monitorInterval).build();
814         ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, intervalBuilder, dataBroker, ItmUtils.DEFAULT_CALLBACK);
815         return monitorInterval;
816     }
817
818     public static List<String> getInternalTunnelInterfaces(DataBroker dataBroker){
819         List<String> tunnelList = new ArrayList<>();
820         Collection<String> internalInterfaces = itmCache.getAllInternalInterfaces();
821         if(internalInterfaces == null) {
822             updateTunnelsCache(dataBroker);
823             internalInterfaces = itmCache.getAllInternalInterfaces();
824         }
825         LOG.debug("ItmUtils.getTunnelList Cache Internal Interfaces size: {} ", internalInterfaces.size());
826         if(internalInterfaces!=null) {
827             tunnelList.addAll(internalInterfaces);
828         }
829         LOG.trace("ItmUtils.getTunnelList Internal: {}", tunnelList);
830         return tunnelList;
831     }
832
833     public static List<String> getTunnelsofTzone(List<HwVtep> hwVteps, String tzone, DataBroker dataBroker, Boolean hwVtepsExist) {
834
835         List<String> tunnels = new ArrayList<>();
836         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
837                 child(TransportZone.class, new TransportZoneKey(tzone)).build();
838         Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
839         if (tZoneOptional.isPresent()) {
840             TransportZone transportZone = tZoneOptional.get();
841             Class<? extends TunnelTypeBase> tunType = transportZone.getTunnelType();
842             if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
843                 for (Subnets sub : transportZone.getSubnets()) {
844                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
845                         for (Vteps vtepLocal : sub.getVteps()) {
846                             for (Vteps vtepRemote : sub.getVteps()) {
847                                 if (!vtepLocal.equals(vtepRemote)) {
848                                     InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(), tunType);
849                                     InstanceIdentifier<InternalTunnel> intIID =
850                                             InstanceIdentifier.builder(TunnelList.class).
851                                                     child(InternalTunnel.class, key).build();
852                                     Optional<InternalTunnel> TunnelsOptional =
853                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
854                                     if (TunnelsOptional.isPresent()) {
855                                         List<String> tunnelInterfaceNames = TunnelsOptional.get().getTunnelInterfaceNames();
856                                         if (tunnelInterfaceNames != null && !tunnelInterfaceNames.isEmpty()) {
857                                             String tunnelInterfaceName = tunnelInterfaceNames.get(0);
858                                             LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
859                                             tunnels.add(tunnelInterfaceName);
860                                         }
861                                     }
862                                 }
863                             }
864                             if(hwVteps!= null && !hwVteps.isEmpty()) {
865                                 for (HwVtep hwVtep : hwVteps) {
866                                     tunnels.add(getExtTunnel(hwVtep.getNode_id(), vtepLocal.getDpnId().toString(),
867                                             tunType, dataBroker));
868                                     tunnels.add(getExtTunnel(vtepLocal.getDpnId().toString(), hwVtep.getNode_id(),
869                                             tunType, dataBroker));
870                                 }
871                             }
872                         }
873                     }
874                 }
875             }
876             if (hwVtepsExist) {
877                 for (HwVtep hwVtep : hwVteps) {
878                     for (HwVtep hwVtepOther : hwVteps) {
879                         if (!hwVtep.getHwIp().equals(hwVtepOther.getHwIp())) {
880                             tunnels.add(getExtTunnel(hwVtep.getNode_id(), hwVtepOther.getNode_id(), tunType, dataBroker));
881                             tunnels.add(getExtTunnel(hwVtepOther.getNode_id(), hwVtep.getNode_id(), tunType, dataBroker));
882                         }
883                     }
884                 }
885             }
886         }
887         return tunnels;
888     }
889
890     public static List<String> getInternalTunnelsofTzone(String tzone, DataBroker dataBroker) {
891         List<String> tunnels = new ArrayList<>();
892         LOG.trace("Getting internal tunnels of {}",tzone);
893         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
894                 child(TransportZone.class, new TransportZoneKey(tzone)).build();
895         Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
896         if (tZoneOptional.isPresent()) {
897             TransportZone transportZone = tZoneOptional.get();
898             if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
899                 for (Subnets sub : transportZone.getSubnets()) {
900                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
901                         for (Vteps vtepLocal : sub.getVteps()) {
902                             for (Vteps vtepRemote : sub.getVteps()) {
903                                 if (!vtepLocal.equals(vtepRemote)) {
904                                     InternalTunnelKey key =
905                                             new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(),
906                                                     transportZone.getTunnelType());
907                                     InstanceIdentifier<InternalTunnel> intIID =
908                                             InstanceIdentifier.builder(TunnelList.class).
909                                                     child(InternalTunnel.class, key).build();
910                                     Optional<InternalTunnel> tunnelsOptional =
911                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
912                                     if (tunnelsOptional.isPresent()) {
913                                         List<String> tunnelInterfaceNames = tunnelsOptional.get()
914                                                 .getTunnelInterfaceNames();
915                                         if (tunnelInterfaceNames != null && !tunnelInterfaceNames.isEmpty()) {
916                                             String tunnelInterfaceName = tunnelInterfaceNames.get(0);
917                                             LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
918                                             tunnels.add(tunnelInterfaceName);
919                                         }
920                                     }
921                                 }
922                             }
923                         }
924                     }
925                 }
926             }
927         }
928         return tunnels;
929     }
930
931     private static String getExtTunnel(String node_id, String dpId,Class<? extends TunnelTypeBase> tunType, DataBroker dataBroker) {
932         LOG.trace("getting ext tunnel for {} and dpId {}",node_id,dpId);
933         ExternalTunnelKey key = getExternalTunnelKey(dpId, node_id, tunType);
934         InstanceIdentifier<ExternalTunnel> intIID = InstanceIdentifier.builder(ExternalTunnelList.class).
935                 child(ExternalTunnel.class, key).build();
936         Optional<ExternalTunnel> tunnelsOptional =
937                 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
938         if (tunnelsOptional.isPresent()) {
939             String tunnelInterfaceName = tunnelsOptional.get().getTunnelInterfaceName();
940             LOG.trace("ext tunnel returned {} ", tunnelInterfaceName);
941             return tunnelInterfaceName;
942         }
943         return null;
944     }
945     public static ExternalTunnelKey getExternalTunnelKey(String dst , String src, Class<? extends TunnelTypeBase> tunType) {
946         if (src.indexOf("physicalswitch") > 0) {
947             src = src.substring(0, src.indexOf("physicalswitch") - 1);
948         }
949         if (dst.indexOf("physicalswitch") > 0) {
950             dst = dst.substring(0, dst.indexOf("physicalswitch") - 1);
951         }
952         return new ExternalTunnelKey(dst, src, tunType);
953     }
954
955     public static List<TunnelEndPoints> getTEPsForDpn( BigInteger srcDpn, List<DPNTEPsInfo> dpnList) {
956         for (DPNTEPsInfo dpn : dpnList) {
957             if( dpn.getDPNID().equals(srcDpn)) {
958                 return dpn.getTunnelEndPoints() ;
959             }
960         }
961         return null ;
962     }
963     public static TunnelList getAllInternalTunnels(DataBroker broker) {
964         InstanceIdentifier<TunnelList> tunnelListInstanceIdentifier = InstanceIdentifier.builder(TunnelList.class).build();
965         return read(LogicalDatastoreType.CONFIGURATION, tunnelListInstanceIdentifier, broker).orNull();
966     }
967     public static InternalTunnel getInternalTunnel(String interfaceName, DataBroker broker) {
968         InternalTunnel internalTunnel = null;
969         internalTunnel = itmCache.getInternalTunnel(interfaceName);
970         if (internalTunnel == null) {
971             updateTunnelsCache(broker);
972             internalTunnel = itmCache.getInternalTunnel(interfaceName);
973         }
974         return internalTunnel;
975     }
976     public static ExternalTunnel getExternalTunnel(String interfaceName, DataBroker broker) {
977         ExternalTunnel externalTunnel = null;
978         externalTunnel = itmCache.getExternalTunnel(interfaceName);
979         if (externalTunnel == null) {
980             updateTunnelsCache(broker);
981             externalTunnel = itmCache.getExternalTunnel(interfaceName);
982         }
983         return externalTunnel;
984     }
985     public static List<ExternalTunnel> getAllExternalTunnels(DataBroker broker) {
986         List<ExternalTunnel> result = null;
987         InstanceIdentifier<ExternalTunnelList> id = InstanceIdentifier.builder(ExternalTunnelList.class).build();
988         Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, id, broker);
989         if (tunnelList.isPresent()) {
990             result = tunnelList.get().getExternalTunnel();
991         }
992         if (result == null) {
993             result = Collections.emptyList();
994         }
995         return result;
996     }
997     public static String convertTunnelTypetoString(Class<? extends TunnelTypeBase> tunType ) {
998         String tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
999         if (tunType.equals(TunnelTypeVxlan.class)) {
1000             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN ;
1001         } else if (tunType.equals(TunnelTypeGre.class)) {
1002             tunnelType = ITMConstants.TUNNEL_TYPE_GRE ;
1003         } else if (tunType.equals(TunnelTypeMplsOverGre.class)) {
1004             tunnelType = ITMConstants.TUNNEL_TYPE_MPLSoGRE;
1005         }
1006         return tunnelType ;
1007     }
1008
1009
1010     public static boolean isItmIfType(Class<? extends InterfaceType> ifType) {
1011         return ifType != null && ifType.isAssignableFrom(Tunnel.class);
1012     }
1013
1014     public static StateTunnelListKey getTunnelStateKey( org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface iface) {
1015         StateTunnelListKey key = null;
1016         if(isItmIfType(iface.getType())) {
1017             key = new StateTunnelListKey(iface.getName());
1018         }
1019         return key;
1020     }
1021
1022     public static void updateTunnelsCache(DataBroker broker) {
1023         List<InternalTunnel> internalTunnels = getAllInternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
1024         for (InternalTunnel tunnel : internalTunnels) {
1025             itmCache.addInternalTunnel(tunnel);
1026         }
1027         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
1028         for (ExternalTunnel tunnel : externalTunnels) {
1029             itmCache.addExternalTunnel(tunnel);
1030         }
1031     }
1032
1033     public static List<ExternalTunnel> getAllExternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
1034         List<ExternalTunnel> result = null;
1035         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1036         Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1037         if (tunnelList.isPresent()) {
1038             result = tunnelList.get().getExternalTunnel();
1039         }
1040         if (result == null) {
1041             result = Collections.emptyList();
1042         }
1043         return result;
1044     }
1045
1046     public static List<InternalTunnel> getAllInternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
1047         List<InternalTunnel> result = null;
1048         InstanceIdentifier<TunnelList> iid = InstanceIdentifier.builder(TunnelList.class).build();
1049         Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1050         if (tunnelList.isPresent()) {
1051             result = tunnelList.get().getInternalTunnel();
1052         }
1053         if (result == null) {
1054             result = Collections.emptyList();
1055         }
1056         return result;
1057     }
1058
1059     public static Interface getInterface(
1060             String name, IInterfaceManager ifaceManager) {
1061         Interface result = itmCache.getInterface(name);
1062         if (result == null) {
1063             result = ifaceManager.getInterfaceInfoFromConfigDataStore(name);
1064             if (result != null) {
1065                 itmCache.addInterface(result);
1066             }
1067         }
1068         return result;
1069     }
1070     public static StateTunnelList getTunnelState(DataBroker dataBroker, String ifaceName,
1071                                                  InstanceIdentifier<StateTunnelList> stListId){
1072         StateTunnelList tunnelState = (StateTunnelList)DataStoreCache.get(ITMConstants.TUNNEL_STATE_CACHE_NAME, ifaceName);
1073         if(tunnelState == null) {
1074             Optional<StateTunnelList> tunnelsState = ItmUtils.read(LogicalDatastoreType.OPERATIONAL, stListId, dataBroker);
1075             if(tunnelsState.isPresent()){
1076                 return tunnelState;
1077             }
1078         }
1079         return tunnelState;
1080     }
1081
1082     public static Class<? extends TunnelMonitoringTypeBase> readMonitoringProtocolFromCache(DataBroker dataBroker) {
1083         InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
1084         TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
1085         if(tunnelMonitorParams!=null) {
1086             return tunnelMonitorParams.getMonitorProtocol();
1087         }
1088         return null;
1089     }
1090
1091     public static Class<? extends TunnelMonitoringTypeBase> determineMonitorProtocol(DataBroker dataBroker) {
1092         Class<? extends TunnelMonitoringTypeBase> monitoringProtocol = ItmUtils.readMonitoringProtocolFromCache(dataBroker);
1093         LOG.debug("determineMonitorProtocol: monitorProtocol from DS = {}", monitoringProtocol);
1094         if(monitoringProtocol==null) {
1095             monitoringProtocol = ITMConstants.DEFAULT_MONITOR_PROTOCOL;
1096         }
1097         LOG.debug("determineMonitorProtocol: monitorProtocol = {}", monitoringProtocol);
1098         Boolean monitorState = ItmUtils.readMonitoringStateFromCache(dataBroker);
1099         if(monitorState==null) {
1100             monitorState = true;
1101         }
1102         LOG.debug("determineMonitorProtocol: monitorState = {}", monitorState);
1103         InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.builder(TunnelMonitorParams.class).build();
1104         TunnelMonitorParams protocolBuilder = new TunnelMonitorParamsBuilder().setEnabled(monitorState).setMonitorProtocol(monitoringProtocol).build();
1105         ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, protocolBuilder, dataBroker, ItmUtils.DEFAULT_CALLBACK);
1106         return monitoringProtocol;
1107     }
1108
1109     public static List<DcGatewayIp> getDcGatewayIpList(DataBroker broker){
1110         InstanceIdentifier<DcGatewayIpList> dcGatewayIpListid = InstanceIdentifier.builder(DcGatewayIpList.class).build();
1111         Optional<DcGatewayIpList> dcGatewayIpListConfig = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, dcGatewayIpListid, broker);
1112         if(dcGatewayIpListConfig.isPresent()){
1113             DcGatewayIpList containerList = dcGatewayIpListConfig.get();
1114             if(containerList != null){
1115                 return containerList.getDcGatewayIp();
1116             }
1117         }
1118         return null;
1119     }
1120
1121     public static boolean falseIfNull(Boolean value) {
1122         return value == null ? false : value;
1123     }
1124
1125     public static <T> List<T> getIntersection(List<T> list1, List<T> list2) {
1126         List<T> list = new ArrayList<>();
1127         for (T t : list1) {
1128             if(list2.contains(t)) {
1129                 list.add(t);
1130             }
1131         }
1132         LOG.debug( " getIntersection - L1 {}, L2 - {}, Intersection - {}", list1, list2, list);
1133         return list;
1134     }
1135
1136     public static void addTransportZoneMembership(List<TzMembership> zones, String zoneName) {
1137         zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());
1138     }
1139
1140     public static  List<TzMembership> createTransportZoneMembership(String zoneName) {
1141         List<TzMembership> zones = new ArrayList<>();
1142         zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());
1143         return zones;
1144     }
1145
1146     /**
1147      * Returns the transport zone from Configuration datastore.
1148      *
1149      * @param tzName transport zone name
1150      * @param dataBroker data broker handle to perform operations on datastore
1151      */
1152     // FIXME: Better is to implement cache to avoid datastore read.
1153     public static TransportZone getTransportZoneFromConfigDS(String tzName, DataBroker dataBroker) {
1154         InstanceIdentifier<TransportZone> tzonePath = InstanceIdentifier.builder(TransportZones.class)
1155             .child(TransportZone.class, new TransportZoneKey(tzName)).build();
1156         Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, tzonePath,
1157             dataBroker);
1158         if (tZoneOptional.isPresent()) {
1159             return tZoneOptional.get();
1160         }
1161         return null;
1162     }
1163
1164     /**
1165      * Gets the transport zone in TepsNotHosted list in the Configuration Datastore
1166      * based on transport zone name
1167      *
1168      * @param unknownTz transport zone name
1169      *
1170      * @param dataBroker data broker handle to perform read operations on config datastore
1171      *
1172      * @return the TepsNotHostedInTransportZone object in the TepsNotHosted list in Config DS
1173      */
1174     public static TepsNotHostedInTransportZone getUnknownTransportZoneFromITMConfigDS(
1175         String unknownTz, DataBroker dataBroker) {
1176         InstanceIdentifier<TepsNotHostedInTransportZone> unknownTzPath =
1177             InstanceIdentifier.builder(TransportZones.class)
1178                 .child(TepsNotHostedInTransportZone.class,
1179                     new TepsNotHostedInTransportZoneKey(unknownTz)).build();
1180         Optional<TepsNotHostedInTransportZone> unknownTzOptional =
1181             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, unknownTzPath, dataBroker);
1182         if (unknownTzOptional.isPresent()) {
1183             return unknownTzOptional.get();
1184         }
1185         return null;
1186     }
1187
1188     /**
1189      * Gets the bridge datapath ID from Network topology Node's OvsdbBridgeAugmentation
1190      * in the Operational DS.
1191      *
1192      * @param node Network Topology Node
1193      *
1194      * @param bridge bridge name
1195      *
1196      * @param dataBroker data broker handle to perform operations on datastore
1197      *
1198      * @return the datapath ID of bridge in string form
1199      */
1200     public static String getBridgeDpid(Node node, String bridge, DataBroker dataBroker) {
1201         OvsdbBridgeAugmentation ovsdbBridgeAugmentation = null;
1202         Node bridgeNode = null;
1203         String datapathId = null;
1204
1205         NodeId ovsdbNodeId = node.getKey().getNodeId();
1206
1207         NodeId brNodeId = new NodeId(ovsdbNodeId.getValue()
1208             + "/" + ITMConstants.BRIDGE_URI_PREFIX + "/" + bridge);
1209
1210         InstanceIdentifier<Node> bridgeIid =
1211             InstanceIdentifier
1212                 .create(NetworkTopology.class)
1213                 .child(Topology.class, new TopologyKey(IfmConstants.OVSDB_TOPOLOGY_ID))
1214                 .child(Node.class,new NodeKey(brNodeId));
1215
1216         Optional<Node> opBridgeNode = ItmUtils.read(LogicalDatastoreType.OPERATIONAL, bridgeIid, dataBroker);
1217
1218         if (opBridgeNode.isPresent()) {
1219             bridgeNode = opBridgeNode.get();
1220         }
1221         if (bridgeNode != null) {
1222             ovsdbBridgeAugmentation = bridgeNode.getAugmentation(OvsdbBridgeAugmentation.class);
1223         }
1224
1225         if (ovsdbBridgeAugmentation != null && ovsdbBridgeAugmentation.getDatapathId() != null) {
1226             datapathId = ovsdbBridgeAugmentation.getDatapathId().getValue();
1227         }
1228         return datapathId;
1229     }
1230
1231     /**
1232      * Gets the Network topology Node from Operational Datastore
1233      * based on Bridge Augmentation.
1234      *
1235      * @param bridgeAugmentation bridge augmentation of OVSDB node
1236      *
1237      * @param dataBroker data broker handle to perform operations on datastore
1238      *
1239      * @return the Network Topology Node i.e. OVSDB node which is managing the specified bridge
1240      */
1241     public static Node getOvsdbNode(OvsdbBridgeAugmentation bridgeAugmentation,
1242         DataBroker dataBroker) {
1243         Node ovsdbNode = null;
1244         Optional<Node> opOvsdbNode = null;
1245         if (bridgeAugmentation != null) {
1246             InstanceIdentifier<Node> ovsdbNodeIid =
1247                 (InstanceIdentifier<Node>) bridgeAugmentation.getManagedBy().getValue();
1248             opOvsdbNode = ItmUtils.read(LogicalDatastoreType.OPERATIONAL, ovsdbNodeIid, dataBroker);
1249         }
1250         if (opOvsdbNode.isPresent()) {
1251             ovsdbNode = opOvsdbNode.get();
1252         }
1253         return ovsdbNode;
1254     }
1255
1256     /**
1257      * Gets the bridge datapath ID in string form from
1258      * Network topology Node's OvsdbBridgeAugmentation in the Operational DS.
1259      *
1260      * @param augmentedNode Ovsdb Augmented Network Topology Node
1261      *
1262      * @return the datapath ID of bridge in string form
1263      */
1264     public static String getStrDatapathId(OvsdbBridgeAugmentation augmentedNode) {
1265         String datapathId = null;
1266         if (augmentedNode != null && augmentedNode.getDatapathId() != null) {
1267             datapathId = augmentedNode.getDatapathId().getValue();
1268         }
1269         return datapathId;
1270     }
1271
1272     /**
1273      * Returns the dummy subnet (255.255.255.255/32) as IpPrefix object
1274      *
1275      * @return the dummy subnet (255.255.255.255/32) in IpPrefix object
1276      */
1277     public static IpPrefix getDummySubnet() {
1278         return DUMMY_IP_PREFIX;
1279     }
1280
1281     /**
1282      * Deletes the transport zone from Configuration datastore.
1283      *
1284      * @param tzName transport zone name
1285      * @param dataBroker data broker handle to perform operations on datastore
1286      */
1287     public static void deleteTransportZoneFromConfigDS(String tzName, DataBroker dataBroker) {
1288         // check whether transport-zone exists in config DS.
1289         TransportZone tZoneFromConfigDS = ItmUtils.getTransportZoneFromConfigDS(tzName, dataBroker);
1290         if (tZoneFromConfigDS != null) {
1291             // it exists, delete default-TZ now
1292             InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class)
1293                 .child(TransportZone.class,
1294                     new TransportZoneKey(tzName)).build();
1295             LOG.debug("Removing {} transport-zone from config DS.", tzName);
1296             ItmUtils.asyncDelete(LogicalDatastoreType.CONFIGURATION, path, dataBroker, ItmUtils.DEFAULT_CALLBACK);
1297         }
1298     }
1299
1300     /**
1301      * Validates the tunnelType argument and returnsTunnelTypeBase class object
1302      * corresponding to tunnelType obtained in String format.
1303      *
1304      * @param tunnelType type of tunnel in string form
1305      *
1306      * @return tunnel-type in TunnelTypeBase object
1307      */
1308     public static Class<? extends TunnelTypeBase> getTunnelType(String tunnelType) {
1309         // validate tunnelType string, in case it is NULL or empty, then
1310         // take VXLAN tunnel type by default
1311         if (tunnelType == null || tunnelType.isEmpty()) {
1312             return TUNNEL_TYPE_MAP.get(ITMConstants.TUNNEL_TYPE_VXLAN);
1313         } else if (!tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN) &&
1314             !tunnelType.equals(ITMConstants.TUNNEL_TYPE_GRE)) {
1315             // if tunnel type is some incorrect value, then
1316             // take VXLAN tunnel type by default
1317             return TUNNEL_TYPE_MAP.get(ITMConstants.TUNNEL_TYPE_VXLAN);
1318         }
1319
1320         // return TunnelTypeBase object corresponding to tunnel-type
1321         return TUNNEL_TYPE_MAP.get(tunnelType);
1322     }
1323
1324     public static List<TzMembership> removeTransportZoneMembership(TunnelEndPoints endPts, List<TzMembership> zones){
1325         LOG.trace( " RemoveTransportZoneMembership TEPs {}, Membership to be removed {} ", endPts, zones);
1326         List<TzMembership> existingTzList = new ArrayList<>(endPts.getTzMembership()) ;
1327         for( TzMembership membership : zones) {
1328             existingTzList.remove(new TzMembershipBuilder().setZoneName(membership.getZoneName()).build());
1329         }
1330         LOG.debug( "Modified Membership List {}", existingTzList);
1331         return existingTzList;
1332     }
1333
1334     public static List<TzMembership> getOriginalTzMembership(TunnelEndPoints srcTep, BigInteger dpnId, List<DPNTEPsInfo> meshedDpnList) {
1335         LOG.trace( "Original Membership for source DPN {}, source TEP {}", dpnId, srcTep) ;
1336         for (DPNTEPsInfo dstDpn : meshedDpnList) {
1337             if( dpnId.equals(dstDpn.getDPNID()) ){
1338                 List<TunnelEndPoints> endPts = dstDpn.getTunnelEndPoints();
1339                 for( TunnelEndPoints tep : endPts) {
1340                     if( tep.getIpAddress().equals( srcTep.getIpAddress())){
1341                         LOG.debug( "Original Membership size " + tep.getTzMembership().size()) ;
1342                         return tep.getTzMembership() ;
1343                     }
1344                 }
1345             }
1346         }
1347         return null ;
1348     }
1349     public static StateTunnelList buildStateTunnelList(StateTunnelListKey tlKey, String name, boolean state, TunnelOperStatus tunOpStatus, IInterfaceManager  ifaceManager, DataBroker broker) {
1350         StateTunnelListBuilder stlBuilder = new StateTunnelListBuilder();
1351         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface iface = ItmUtils
1352                 .getInterface(name, ifaceManager);
1353         IfTunnel ifTunnel = iface.getAugmentation(IfTunnel.class);
1354         ParentRefs parentRefs = iface.getAugmentation(ParentRefs.class);
1355         if (ifTunnel == null && parentRefs == null) {
1356             return null;
1357         }
1358         DstInfoBuilder dstInfoBuilder = new DstInfoBuilder();
1359         SrcInfoBuilder srcInfoBuilder = new SrcInfoBuilder();
1360         dstInfoBuilder.setTepIp(ifTunnel.getTunnelDestination());
1361         srcInfoBuilder.setTepIp(ifTunnel.getTunnelSource());
1362         // TODO: Add/Improve logic for device type
1363         InternalTunnel internalTunnel = ItmUtils.itmCache.getInternalTunnel(name);
1364         ExternalTunnel externalTunnel = ItmUtils.itmCache.getExternalTunnel(name);
1365         if (internalTunnel == null && externalTunnel == null) {
1366             // both not present in cache. let us update and try again.
1367             ItmUtils.updateTunnelsCache(broker);
1368             internalTunnel = ItmUtils.itmCache.getInternalTunnel(name);
1369             externalTunnel = ItmUtils.itmCache.getExternalTunnel(name);
1370         }
1371         if (internalTunnel != null) {
1372             srcInfoBuilder.setTepDeviceId(internalTunnel.getSourceDPN().toString())
1373                     .setTepDeviceType(TepTypeInternal.class);
1374             dstInfoBuilder.setTepDeviceId(internalTunnel.getDestinationDPN().toString())
1375                     .setTepDeviceType(TepTypeInternal.class);
1376             stlBuilder.setTransportType(internalTunnel.getTransportType());
1377         } else if (externalTunnel != null) {
1378             ExternalTunnel tunnel = ItmUtils.itmCache.getExternalTunnel(name);
1379             srcInfoBuilder.setTepDeviceId(tunnel.getSourceDevice())
1380                     .setTepDeviceType(getDeviceType(tunnel.getSourceDevice()));
1381             dstInfoBuilder.setTepDeviceId(tunnel.getDestinationDevice())
1382                     .setTepDeviceType(getDeviceType(tunnel.getDestinationDevice()))
1383                     .setTepIp(ifTunnel.getTunnelDestination());
1384             stlBuilder.setTransportType(tunnel.getTransportType());
1385         }
1386         stlBuilder.setKey(tlKey).setTunnelInterfaceName(name).setOperState(tunOpStatus).setTunnelState(state)
1387                 .setDstInfo(dstInfoBuilder.build()).setSrcInfo(srcInfoBuilder.build());
1388         return stlBuilder.build();
1389     }
1390     public static Class<? extends TepTypeBase> getDeviceType(String device) {
1391         if (device.startsWith("hwvtep")) {
1392             return TepTypeHwvtep.class;
1393         } else if (device.contains("IpAddress")) {
1394             return TepTypeExternal.class;
1395         } else {
1396             return TepTypeInternal.class;
1397         }
1398     }
1399
1400     public static InstanceIdentifier<StateTunnelList> buildStateTunnelListId(StateTunnelListKey tlKey) {
1401         return InstanceIdentifier.builder(TunnelsState.class)
1402                 .child(StateTunnelList.class, tlKey).build();
1403     }
1404 }