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