Merge "Fcaps: changing alarm text parameter to be same while raising and clearing"
[genius.git] / itm / itm-impl / src / main / java / org / opendaylight / genius / itm / impl / ItmUtils.java
1 /*
2  * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.genius.itm.impl;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.net.InetAddresses;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import java.math.BigInteger;
17 import java.net.InetAddress;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.List;
22 import java.util.UUID;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.Future;
25 import org.apache.commons.lang3.StringUtils;
26 import org.apache.commons.net.util.SubnetUtils;
27 import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
28 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
29 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
30 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
31 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
32 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
33 import org.opendaylight.genius.itm.api.IITMProvider;
34 import org.opendaylight.genius.itm.confighelpers.HwVtep;
35 import org.opendaylight.genius.itm.globals.ITMConstants;
36 import org.opendaylight.genius.mdsalutil.ActionInfo;
37 import org.opendaylight.genius.mdsalutil.ActionType;
38 import org.opendaylight.genius.mdsalutil.FlowEntity;
39 import org.opendaylight.genius.mdsalutil.InstructionInfo;
40 import org.opendaylight.genius.mdsalutil.InstructionType;
41 import org.opendaylight.genius.mdsalutil.MDSALUtil;
42 import org.opendaylight.genius.mdsalutil.MatchFieldType;
43 import org.opendaylight.genius.mdsalutil.MatchInfo;
44 import org.opendaylight.genius.mdsalutil.NwConstants;
45 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.Tunnel;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlan;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlanBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnelBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefsBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelMonitoringTypeBase;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeGre;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeMplsOverGre;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifier;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierBuilder;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierKey;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorInterval;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorIntervalBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorParams;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorParamsBuilder;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.VtepConfigSchemas;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.VtepIpPools;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchema;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaKey;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIds;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsKey;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPool;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPoolKey;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpoints;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpointsBuilder;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelList;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfo;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoBuilder;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoKey;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPoints;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsBuilder;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsKey;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.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 ActionInfo(ActionType.punt_to_controller,
443                 new String[] {}));
444
445         try {
446             List<MatchInfo> mkMatches = new ArrayList<>();
447
448             mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {
449                     BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID) }));
450
451             List<InstructionInfo> mkInstructions = new ArrayList<>();
452             mkInstructions.add(new InstructionInfo(InstructionType.apply_actions,
453                     listActionInfo));
454
455             FlowEntity terminatingServiceTableFlowEntity = MDSALUtil
456                     .buildFlowEntity(
457                             dpnId,
458                             NwConstants.INTERNAL_TUNNEL_TABLE,
459                             getFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE,
460                                     ITMConstants.LLDP_SERVICE_ID), 5, String.format("%s:%d","ITM Flow Entry ",ITMConstants.LLDP_SERVICE_ID),
461                             0, 0, ITMConstants.COOKIE_ITM
462                                     .add(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)),
463                             mkMatches, mkInstructions);
464             if(addFlag) {
465                 mdsalManager.installFlow(terminatingServiceTableFlowEntity);
466             } else {
467                 mdsalManager.removeFlow(terminatingServiceTableFlowEntity);
468             }
469         } catch (Exception e) {
470             LOG.error("Error while setting up Table 36 for {}", dpnId, e);
471         }
472     }
473
474     private static String getFlowRef(long termSvcTable, int svcId) {
475         return String.valueOf(termSvcTable) + svcId;
476     }
477     public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier(String schemaName) {
478         return InstanceIdentifier.builder(VtepConfigSchemas.class)
479                 .child(VtepConfigSchema.class, new VtepConfigSchemaKey(schemaName)).build();
480     }
481
482     public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier() {
483         return InstanceIdentifier.builder(VtepConfigSchemas.class).child(VtepConfigSchema.class).build();
484     }
485     public static InstanceIdentifier<VtepConfigSchemas> getVtepConfigSchemasIdentifier() {
486         return InstanceIdentifier.builder(VtepConfigSchemas.class).build();
487     }
488     public static InstanceIdentifier<VtepIpPool> getVtepIpPoolIdentifier(String subnetCidr) {
489         return InstanceIdentifier.builder(VtepIpPools.class).child(VtepIpPool.class, new VtepIpPoolKey(subnetCidr))
490                 .build();
491     }
492     public static VtepConfigSchema validateForAddVtepConfigSchema(VtepConfigSchema schema,
493                                                                   List<VtepConfigSchema> existingSchemas) {
494         VtepConfigSchema validSchema = validateVtepConfigSchema(schema);
495         for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
496             if (!StringUtils.equalsIgnoreCase(schema.getSchemaName(), existingSchema.getSchemaName())
497                     && schema.getSubnet().equals(existingSchema.getSubnet())) {
498                 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
499                 Preconditions.checkArgument(false, "VTEP schema with subnet [" + subnetCidr +
500                         "] already exists. Multiple VTEP schemas with same subnet is not allowed.");
501             }
502         }
503         if (isNotEmpty(getDpnIdList(validSchema.getDpnIds()))) {
504             String tzone = validSchema.getTransportZoneName();
505             List<BigInteger> lstDpns = getConflictingDpnsAlreadyConfiguredWithTz(validSchema.getSchemaName(), tzone,
506                     getDpnIdList(validSchema.getDpnIds()), existingSchemas);
507             if (!lstDpns.isEmpty()) {
508                 Preconditions.checkArgument(false,
509                         "DPN's " + lstDpns + " already configured for transport zone " +
510                                 tzone + ". Only one end point per transport Zone per Dpn is allowed.");
511             }
512             if (schema.getTunnelType().equals(TunnelTypeGre.class)){
513                 validateForSingleGreTep(validSchema.getSchemaName(), getDpnIdList(validSchema.getDpnIds()), existingSchemas);
514             }
515         }
516         return validSchema;
517     }
518     private static void validateForSingleGreTep(String schemaName, List<BigInteger> lstDpnsForAdd,
519                                                 List<VtepConfigSchema> existingSchemas) {
520         for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
521             if (TunnelTypeGre.class.equals(existingSchema.getTunnelType())
522                     && !StringUtils.equalsIgnoreCase(schemaName, existingSchema.getSchemaName())) {
523                 List<BigInteger> lstConflictingDpns = new ArrayList<>(getDpnIdList(existingSchema.getDpnIds()));
524                 lstConflictingDpns.retainAll(emptyIfNull(lstDpnsForAdd));
525                 if (!lstConflictingDpns.isEmpty()) {
526                     String errMsg = "DPN's " + lstConflictingDpns +
527                             " already configured with GRE TEP. Mutiple GRE TEP's on a single DPN are not allowed.";
528                     Preconditions.checkArgument(false, errMsg);
529                 }
530             }
531         }
532     }
533     public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
534         Preconditions.checkNotNull(schema);
535         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
536         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
537         Preconditions.checkArgument(schema.getVlanId() >= 0 && schema.getVlanId() < 4095,
538                 "Invalid VLAN ID, range (0-4094)");
539         Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
540         Preconditions.checkNotNull(schema.getSubnet());
541         String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
542         SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
543         IpAddress gatewayIp = schema.getGatewayIp();
544         if (gatewayIp != null) {
545             String strGatewayIp = String.valueOf(gatewayIp.getValue());
546             if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS) && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
547                 Preconditions.checkArgument(false, "Gateway IP address " + strGatewayIp +
548                         " is not in subnet range " + subnetCidr);
549             }
550         }
551         ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
552         return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
553     }
554     public static String validateTunnelType(String tunnelType) {
555         if (tunnelType == null) {
556             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
557         } else {
558             tunnelType = StringUtils.upperCase(tunnelType);
559             String error = "Invalid tunnel type. Valid values: " +
560                     ITMConstants.TUNNEL_TYPE_VXLAN + " | " + ITMConstants.TUNNEL_TYPE_GRE;
561             Preconditions.checkArgument(ITMConstants.TUNNEL_TYPE_VXLAN.equals(tunnelType)
562                     || ITMConstants.TUNNEL_TYPE_GRE.equals(tunnelType), error);
563         }
564         return tunnelType;
565     }
566     private static List<BigInteger> getConflictingDpnsAlreadyConfiguredWithTz(String schemaName, String tzone,
567                                                                               List<BigInteger> lstDpns, List<VtepConfigSchema> existingSchemas) {
568         List<BigInteger> lstConflictingDpns = new ArrayList<>();
569         for (VtepConfigSchema schema : emptyIfNull(existingSchemas)) {
570             if (!StringUtils.equalsIgnoreCase(schemaName, schema.getSchemaName())
571                     && StringUtils.equals(schema.getTransportZoneName(), tzone)) {
572                 lstConflictingDpns = new ArrayList<>(getDpnIdList(schema.getDpnIds()));
573                 lstConflictingDpns.retainAll(lstDpns);
574                 if (!lstConflictingDpns.isEmpty()) {
575                     break;
576                 }
577             }
578         }
579         return lstConflictingDpns;
580     }
581     public static VtepConfigSchema constructVtepConfigSchema(String schemaName, String portName, Integer vlanId,
582                                                              String subnetMask, String gatewayIp, String transportZone,String tunnelType, List<BigInteger> dpnIds,
583                                                              String excludeIpFilter) {
584         IpAddress gatewayIpObj = StringUtils.isBlank(gatewayIp) ? null : new IpAddress(gatewayIp.toCharArray());
585         IpPrefix subnet = StringUtils.isBlank(subnetMask) ? null : new IpPrefix(subnetMask.toCharArray());
586         Class<? extends TunnelTypeBase> tunType ;
587         if( tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN)) {
588             tunType = TunnelTypeVxlan.class ;
589         } else {
590             tunType = TunnelTypeGre.class ;
591         }
592         VtepConfigSchemaBuilder schemaBuilder = new VtepConfigSchemaBuilder().setSchemaName(schemaName)
593                 .setPortName(portName).setVlanId(vlanId).setSubnet(subnet).setGatewayIp(gatewayIpObj)
594                 .setTransportZoneName(transportZone).setTunnelType(tunType).setDpnIds(getDpnIdsListFromBigInt(dpnIds))
595                 .setExcludeIpFilter(excludeIpFilter);
596         return schemaBuilder.build();
597     }
598     public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
599         final List<IpAddress> lstIpAddress = new ArrayList<>();
600         if (StringUtils.isBlank(excludeIpFilter)) {
601             return lstIpAddress;
602         }
603         final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
604         for (String ip : arrIps) {
605             if (StringUtils.countMatches(ip, "-") == 1) {
606                 final String[] arrIpRange = StringUtils.split(ip, '-');
607                 String strStartIp = StringUtils.trim(arrIpRange[0]);
608                 String strEndIp = StringUtils.trim(arrIpRange[1]);
609                 Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
610                         "Invalid exclude IP filter: invalid IP address value " + strStartIp);
611                 Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
612                         "Invalid exclude IP filter: invalid IP address value " + strEndIp);
613                 Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
614                         "Invalid exclude IP filter: IP address [" + strStartIp +
615                                 "] not in subnet range " + subnetInfo.getCidrSignature());
616                 Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
617                         "Invalid exclude IP filter: IP address [" + strEndIp +
618                                 "] not in subnet range " + subnetInfo.getCidrSignature());
619                 int startIp = subnetInfo.asInteger(strStartIp);
620                 int endIp = subnetInfo.asInteger(strEndIp);
621
622                 Preconditions.checkArgument(startIp < endIp,
623                         "Invalid exclude IP filter: Invalid range [" + ip + "] ");
624                 for (int i = startIp; i <= endIp; i++) {
625                     String ipAddress = ipFormat(toIpArray(i));
626                     validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
627                 }
628             } else {
629                 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
630             }
631         }
632         return lstIpAddress;
633     }
634     private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
635                                                       String ipAddress) {
636         String ip = StringUtils.trim(ipAddress);
637         Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
638                 "Invalid exclude IP filter: invalid IP address value " + ip);
639         Preconditions.checkArgument(subnetInfo.isInRange(ip),
640                 "Invalid exclude IP filter: IP address [" + ip + "] not in subnet range " +
641                         subnetInfo.getCidrSignature());
642         lstIpAddress.add(new IpAddress(ip.toCharArray()));
643     }
644     private static int[] toIpArray(int val) {
645         int[] ret = new int[4];
646         for (int j = 3; j >= 0; --j) {
647             ret[j] |= val >>> 8 * (3 - j) & 0xff;
648         }
649         return ret;
650     }
651     private static String ipFormat(int[] octets) {
652         StringBuilder str = new StringBuilder();
653         for (int i = 0; i < octets.length; ++i) {
654             str.append(octets[i]);
655             if (i != octets.length - 1) {
656                 str.append(".");
657             }
658         }
659         return str.toString();
660     }
661     public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd,
662                                                                List<BigInteger> lstDpnsForDelete, IITMProvider itmProvider) {
663         Preconditions.checkArgument(StringUtils.isNotBlank(schemaName));
664         if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty())
665                 && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) {
666             Preconditions.checkArgument(false,
667                     "DPN ID list for add | delete is null or empty in schema " + schemaName);
668         }
669         VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName);
670         if (schema == null) {
671             Preconditions.checkArgument(false, "Specified VTEP Schema [" + schemaName +
672                     "] doesn't exists!");
673         }
674         List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds());
675         if (isNotEmpty(lstDpnsForAdd)) {
676             //  if (isNotEmpty(existingDpnIds)) {
677             List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds);
678             lstAlreadyExistingDpns.retainAll(lstDpnsForAdd);
679             Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(),
680                     "DPN ID's " + lstAlreadyExistingDpns +
681                             " already exists in VTEP schema [" + schemaName + "]");
682             //    }
683             if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
684                 validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd, itmProvider.getAllVtepConfigSchemas());
685             }
686         }
687         if (isNotEmpty(lstDpnsForDelete)) {
688             if (existingDpnIds == null || existingDpnIds.isEmpty()) {
689                 String builder = "DPN ID's " + lstDpnsForDelete +
690                         " specified for delete from VTEP schema [" + schemaName +
691                         "] are not configured in the schema.";
692                 Preconditions.checkArgument(false, builder);
693             } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) {
694                 List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete);
695                 lstConflictingDpns.removeAll(existingDpnIds);
696                 String builder = "DPN ID's " + lstConflictingDpns +
697                         " specified for delete from VTEP schema [" + schemaName +
698                         "] are not configured in the schema.";
699                 Preconditions.checkArgument(false, builder);
700             }
701         }
702         return schema;
703     }
704     public static String getSubnetCidrAsString(IpPrefix subnet) {
705         return subnet == null ? StringUtils.EMPTY : String.valueOf(subnet.getValue());
706     }
707     public static <T> List<T> emptyIfNull(List<T> list) {
708         return list == null ? Collections.emptyList() : list;
709     }
710     public static <T> boolean isEmpty(Collection<T> collection) {
711         return collection == null || collection.isEmpty();
712     }
713     public static <T> boolean isNotEmpty(Collection<T> collection) {
714         return !isEmpty(collection);
715     }
716     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) {
717         HwVtep hwVtep = new HwVtep();
718         hwVtep.setGatewayIP(gatewayIP);
719         hwVtep.setHwIp(ipAddress);
720         hwVtep.setIpPrefix(ipPrefix);
721         hwVtep.setNode_id(node_id);
722         hwVtep.setTopo_id(topo_id);
723         hwVtep.setTransportZone(transportZone.getZoneName());
724         hwVtep.setTunnel_type(tunnel_type);
725         hwVtep.setVlanID(vlanID);
726         return hwVtep;
727     }
728
729     public static String getHwParentIf(String topo_id, String srcNodeid) {
730         return String.format("%s:%s", topo_id, srcNodeid);
731     }
732
733     public static <T extends DataObject> void syncWrite(LogicalDatastoreType datastoreType,
734                                                         InstanceIdentifier<T> path, T data, DataBroker broker) {
735         WriteTransaction tx = broker.newWriteOnlyTransaction();
736         tx.put(datastoreType, path, data, true);
737         CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
738         try {
739             futures.get();
740         } catch (InterruptedException | ExecutionException e) {
741             LOG.error("ITMUtils:SyncWrite , Error writing to datastore (path, data) : ({}, {})", path, data);
742             throw new RuntimeException(e.getMessage());
743         }
744     }
745
746     public static List<BigInteger> getDpnIdList( List<DpnIds> dpnIds ) {
747         List<BigInteger> dpnList = new ArrayList<>() ;
748         for( DpnIds dpn : dpnIds) {
749             dpnList.add(dpn.getDPN()) ;
750         }
751         return dpnList ;
752     }
753
754     public static List<DpnIds> getDpnIdsListFromBigInt( List<BigInteger> dpnIds) {
755         List<DpnIds> dpnIdList = new ArrayList<>() ;
756         DpnIdsBuilder builder = new DpnIdsBuilder() ;
757         for( BigInteger dpnId : dpnIds) {
758             dpnIdList.add(builder.setKey(new DpnIdsKey(dpnId)).setDPN(dpnId).build() );
759         }
760         return dpnIdList;
761     }
762
763     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
764         InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder =
765                 InstanceIdentifier.builder(InterfacesState.class)
766                         .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.class,
767                                 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
768                                         interfaceName));
769         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> id = idBuilder.build();
770         return id;
771     }
772     public static Boolean readMonitoringStateFromCache(DataBroker dataBroker) {
773         InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
774         TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
775         if(tunnelMonitorParams!=null) {
776             return tunnelMonitorParams.isEnabled();
777         } else {
778             return ITMConstants.DEFAULT_MONITOR_ENABLED;
779         }
780     }
781
782     public static Integer readMonitorIntervalfromCache(DataBroker dataBroker) {
783         InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.create(TunnelMonitorInterval.class);
784         TunnelMonitorInterval tunnelMonitorIOptional = (TunnelMonitorInterval)DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"Interval",dataBroker,true);
785         if(tunnelMonitorIOptional!=null) {
786             return tunnelMonitorIOptional.getInterval();
787         }
788         return null;
789
790     }
791
792     public static Integer determineMonitorInterval(DataBroker dataBroker) {
793         Integer monitorInterval = ItmUtils.readMonitorIntervalfromCache(dataBroker);
794         LOG.debug("determineMonitorInterval: monitorInterval from DS = {}", monitorInterval);
795         if(monitorInterval==null){
796             Class<? extends TunnelMonitoringTypeBase> monitorProtocol = determineMonitorProtocol(dataBroker);
797             if(monitorProtocol.isAssignableFrom(TunnelMonitoringTypeBfd.class)) {
798                 monitorInterval = ITMConstants.BFD_DEFAULT_MONITOR_INTERVAL;
799             } else {
800                 monitorInterval = ITMConstants.DEFAULT_MONITOR_INTERVAL;
801             }
802         }
803         LOG.debug("determineMonitorInterval: monitorInterval = {}", monitorInterval);
804         InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.builder(TunnelMonitorInterval.class).build();
805         TunnelMonitorInterval intervalBuilder = new TunnelMonitorIntervalBuilder().setInterval(monitorInterval).build();
806         ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, intervalBuilder, dataBroker, ItmUtils.DEFAULT_CALLBACK);
807         return monitorInterval;
808     }
809
810     public static List<String> getInternalTunnelInterfaces(DataBroker dataBroker){
811         List<String> tunnelList = new ArrayList<>();
812         Collection<String> internalInterfaces = itmCache.getAllInternalInterfaces();
813         if(internalInterfaces == null) {
814             updateTunnelsCache(dataBroker);
815             internalInterfaces = itmCache.getAllInternalInterfaces();
816         }
817         LOG.debug("ItmUtils.getTunnelList Cache Internal Interfaces size: {} ", internalInterfaces.size());
818         if(internalInterfaces!=null) {
819             tunnelList.addAll(internalInterfaces);
820         }
821         LOG.trace("ItmUtils.getTunnelList Internal: {}", tunnelList);
822         return tunnelList;
823     }
824
825     public static List<String> getTunnelsofTzone(List<HwVtep> hwVteps, String tzone, DataBroker dataBroker, Boolean hwVtepsExist) {
826
827         List<String> tunnels = new ArrayList<>();
828         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
829                 child(TransportZone.class, new TransportZoneKey(tzone)).build();
830         Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
831         if (tZoneOptional.isPresent()) {
832             TransportZone transportZone = tZoneOptional.get();
833             Class<? extends TunnelTypeBase> tunType = transportZone.getTunnelType();
834             if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
835                 for (Subnets sub : transportZone.getSubnets()) {
836                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
837                         for (Vteps vtepLocal : sub.getVteps()) {
838                             for (Vteps vtepRemote : sub.getVteps()) {
839                                 if (!vtepLocal.equals(vtepRemote)) {
840                                     InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(), tunType);
841                                     InstanceIdentifier<InternalTunnel> intIID =
842                                             InstanceIdentifier.builder(TunnelList.class).
843                                                     child(InternalTunnel.class, key).build();
844                                     Optional<InternalTunnel> TunnelsOptional =
845                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
846                                     if (TunnelsOptional.isPresent()) {
847                                         String tunnelInterfaceName = TunnelsOptional.get().getTunnelInterfaceName();
848                                         LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
849                                         tunnels.add(tunnelInterfaceName);
850                                     }
851                                 }
852                             }
853                             if(hwVteps!= null && !hwVteps.isEmpty()) {
854                                 for (HwVtep hwVtep : hwVteps) {
855                                     tunnels.add(getExtTunnel(hwVtep.getNode_id(), vtepLocal.getDpnId().toString(),
856                                             tunType, dataBroker));
857                                     tunnels.add(getExtTunnel(vtepLocal.getDpnId().toString(), hwVtep.getNode_id(),
858                                             tunType, dataBroker));
859                                 }
860                             }
861                         }
862                     }
863                 }
864             }
865             if (hwVtepsExist) {
866                 for (HwVtep hwVtep : hwVteps) {
867                     for (HwVtep hwVtepOther : hwVteps) {
868                         if (!hwVtep.getHwIp().equals(hwVtepOther.getHwIp())) {
869                             tunnels.add(getExtTunnel(hwVtep.getNode_id(), hwVtepOther.getNode_id(), tunType, dataBroker));
870                             tunnels.add(getExtTunnel(hwVtepOther.getNode_id(), hwVtep.getNode_id(), tunType, dataBroker));
871                         }
872                     }
873                 }
874             }
875         }
876         return tunnels;
877     }
878
879     public static List<String> getInternalTunnelsofTzone(String tzone, DataBroker dataBroker) {
880         List<String> tunnels = new ArrayList<>();
881         LOG.trace("Getting internal tunnels of {}",tzone);
882         InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
883                 child(TransportZone.class, new TransportZoneKey(tzone)).build();
884         Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
885         if (tZoneOptional.isPresent()) {
886             TransportZone transportZone = tZoneOptional.get();
887             if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
888                 for (Subnets sub : transportZone.getSubnets()) {
889                     if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
890                         for (Vteps vtepLocal : sub.getVteps()) {
891                             for (Vteps vtepRemote : sub.getVteps()) {
892                                 if (!vtepLocal.equals(vtepRemote)) {
893                                     InternalTunnelKey key =
894                                             new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(),
895                                                     transportZone.getTunnelType());
896                                     InstanceIdentifier<InternalTunnel> intIID =
897                                             InstanceIdentifier.builder(TunnelList.class).
898                                                     child(InternalTunnel.class, key).build();
899                                     Optional<InternalTunnel> tunnelsOptional =
900                                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
901                                     if (tunnelsOptional.isPresent()) {
902                                         String tunnelInterfaceName = tunnelsOptional.get().getTunnelInterfaceName();
903                                         LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
904                                         tunnels.add(tunnelInterfaceName);
905                                     }
906                                 }
907                             }
908                         }
909                     }
910                 }
911             }
912         }
913         return tunnels;
914     }
915
916     private static String getExtTunnel(String node_id, String dpId,Class<? extends TunnelTypeBase> tunType, DataBroker dataBroker) {
917         LOG.trace("getting ext tunnel for {} and dpId {}",node_id,dpId);
918         ExternalTunnelKey key = getExternalTunnelKey(dpId, node_id, tunType);
919         InstanceIdentifier<ExternalTunnel> intIID = InstanceIdentifier.builder(ExternalTunnelList.class).
920                 child(ExternalTunnel.class, key).build();
921         Optional<ExternalTunnel> tunnelsOptional =
922                 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
923         if (tunnelsOptional.isPresent()) {
924             String tunnelInterfaceName = tunnelsOptional.get().getTunnelInterfaceName();
925             LOG.trace("ext tunnel returned {} ", tunnelInterfaceName);
926             return tunnelInterfaceName;
927         }
928         return null;
929     }
930     public static ExternalTunnelKey getExternalTunnelKey(String dst , String src, Class<? extends TunnelTypeBase> tunType) {
931         if (src.indexOf("physicalswitch") > 0) {
932             src = src.substring(0, src.indexOf("physicalswitch") - 1);
933         }
934         if (dst.indexOf("physicalswitch") > 0) {
935             dst = dst.substring(0, dst.indexOf("physicalswitch") - 1);
936         }
937         return new ExternalTunnelKey(dst, src, tunType);
938     }
939
940     public static List<TunnelEndPoints> getTEPsForDpn( BigInteger srcDpn, List<DPNTEPsInfo> dpnList) {
941         for (DPNTEPsInfo dpn : dpnList) {
942             if( dpn.getDPNID().equals(srcDpn)) {
943                 return dpn.getTunnelEndPoints() ;
944             }
945         }
946         return null ;
947     }
948     public static TunnelList getAllInternalTunnels(DataBroker broker) {
949         InstanceIdentifier<TunnelList> tunnelListInstanceIdentifier = InstanceIdentifier.builder(TunnelList.class).build();
950         return read(LogicalDatastoreType.CONFIGURATION, tunnelListInstanceIdentifier, broker).orNull();
951     }
952     public static InternalTunnel getInternalTunnel(String interfaceName, DataBroker broker) {
953         InternalTunnel internalTunnel = null;
954         TunnelList tunnelList = getAllInternalTunnels(broker);
955         if (tunnelList != null && tunnelList.getInternalTunnel() != null) {
956             List<InternalTunnel> internalTunnels = tunnelList.getInternalTunnel();
957             for (InternalTunnel tunnel : internalTunnels) {
958                 if (tunnel.getTunnelInterfaceName().equalsIgnoreCase(interfaceName)) {
959                     internalTunnel = tunnel;
960                     break;
961                 }
962             }
963         }
964         return internalTunnel;
965     }
966     public static ExternalTunnel getExternalTunnel(String interfaceName, DataBroker broker) {
967         ExternalTunnel externalTunnel = null;
968         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker);
969         for (ExternalTunnel tunnel : externalTunnels) {
970             if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
971                 externalTunnel = tunnel;
972                 break;
973             }
974         }
975         return externalTunnel;
976     }
977     public static List<ExternalTunnel> getAllExternalTunnels(DataBroker broker) {
978         List<ExternalTunnel> result = null;
979         InstanceIdentifier<ExternalTunnelList> id = InstanceIdentifier.builder(ExternalTunnelList.class).build();
980         Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, id, broker);
981         if (tunnelList.isPresent()) {
982             result = tunnelList.get().getExternalTunnel();
983         }
984         if (result == null) {
985             result = Collections.emptyList();
986         }
987         return result;
988     }
989     public static String convertTunnelTypetoString(Class<? extends TunnelTypeBase> tunType ) {
990         String tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
991         if( tunType.equals(TunnelTypeVxlan.class)) {
992             tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN ;
993         } else if( tunType.equals(TunnelTypeGre.class) ) {
994             tunnelType = ITMConstants.TUNNEL_TYPE_GRE ;
995         } else if (tunnelType.equals(TunnelTypeMplsOverGre.class)) {
996             tunnelType = ITMConstants.TUNNEL_TYPE_MPLSoGRE;
997         }
998         return tunnelType ;
999     }
1000
1001
1002     public static boolean isItmIfType(Class<? extends InterfaceType> ifType) {
1003         return ifType != null && ifType.isAssignableFrom(Tunnel.class);
1004     }
1005
1006     public static StateTunnelListKey getTunnelStateKey( org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface iface) {
1007         StateTunnelListKey key = null;
1008         if(isItmIfType(iface.getType())) {
1009             key = new StateTunnelListKey(iface.getName());
1010         }
1011         return key;
1012     }
1013
1014     public static void updateTunnelsCache(DataBroker broker) {
1015         List<InternalTunnel> internalTunnels = getAllInternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
1016         for (InternalTunnel tunnel : internalTunnels) {
1017             itmCache.addInternalTunnel(tunnel);
1018         }
1019         List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
1020         for (ExternalTunnel tunnel : externalTunnels) {
1021             itmCache.addExternalTunnel(tunnel);
1022         }
1023     }
1024
1025     public static List<ExternalTunnel> getAllExternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
1026         List<ExternalTunnel> result = null;
1027         InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1028         Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1029         if (tunnelList.isPresent()) {
1030             result = tunnelList.get().getExternalTunnel();
1031         }
1032         if (result == null) {
1033             result = Collections.emptyList();
1034         }
1035         return result;
1036     }
1037
1038     public static List<InternalTunnel> getAllInternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
1039         List<InternalTunnel> result = null;
1040         InstanceIdentifier<TunnelList> iid = InstanceIdentifier.builder(TunnelList.class).build();
1041         Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1042         if (tunnelList.isPresent()) {
1043             result = tunnelList.get().getInternalTunnel();
1044         }
1045         if (result == null) {
1046             result = Collections.emptyList();
1047         }
1048         return result;
1049     }
1050
1051     public static Interface getInterface(
1052             String name, DataBroker broker) {
1053         Interface result = itmCache.getInterface(name);
1054         if (result == null) {
1055             InstanceIdentifier<Interface> iid =
1056                     InstanceIdentifier.builder(Interfaces.class)
1057                             .child(Interface.class, new InterfaceKey(name)).build();
1058             Optional<Interface> optInterface = read(LogicalDatastoreType.CONFIGURATION, iid, broker);
1059             if (optInterface.isPresent()) {
1060                 result = optInterface.get();
1061                 itmCache.addInterface(result);
1062             }
1063         }
1064         return result;
1065     }
1066
1067     public static Class<? extends TunnelMonitoringTypeBase> readMonitoringProtocolFromCache(DataBroker dataBroker) {
1068         InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
1069         TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
1070         if(tunnelMonitorParams!=null) {
1071             return tunnelMonitorParams.getMonitorProtocol();
1072         }
1073         return null;
1074     }
1075
1076     public static Class<? extends TunnelMonitoringTypeBase> determineMonitorProtocol(DataBroker dataBroker) {
1077         Class<? extends TunnelMonitoringTypeBase> monitoringProtocol = ItmUtils.readMonitoringProtocolFromCache(dataBroker);
1078         LOG.debug("determineMonitorProtocol: monitorProtocol from DS = {}", monitoringProtocol);
1079         if(monitoringProtocol==null) {
1080             monitoringProtocol = ITMConstants.DEFAULT_MONITOR_PROTOCOL;
1081         }
1082         LOG.debug("determineMonitorProtocol: monitorProtocol = {}", monitoringProtocol);
1083         Boolean monitorState = ItmUtils.readMonitoringStateFromCache(dataBroker);
1084         if(monitorState==null) {
1085             monitorState = true;
1086         }
1087         LOG.debug("determineMonitorProtocol: monitorState = {}", monitorState);
1088         InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.builder(TunnelMonitorParams.class).build();
1089         TunnelMonitorParams protocolBuilder = new TunnelMonitorParamsBuilder().setEnabled(monitorState).setMonitorProtocol(monitoringProtocol).build();
1090         ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, protocolBuilder, dataBroker, ItmUtils.DEFAULT_CALLBACK);
1091         return monitoringProtocol;
1092     }
1093
1094     public static List<DcGatewayIp> getDcGatewayIpList(DataBroker broker){
1095         InstanceIdentifier<DcGatewayIpList> dcGatewayIpListid = InstanceIdentifier.builder(DcGatewayIpList.class).build();
1096         Optional<DcGatewayIpList> dcGatewayIpListConfig = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, dcGatewayIpListid, broker);
1097         if(dcGatewayIpListConfig.isPresent()){
1098             DcGatewayIpList containerList = dcGatewayIpListConfig.get();
1099             if(containerList != null){
1100                 return containerList.getDcGatewayIp();
1101             }
1102         }
1103         return null;
1104     }
1105
1106     public static boolean falseIfNull(Boolean value) {
1107         return value == null ? false : value;
1108     }
1109
1110     public static <T> List<T> getIntersection(List<T> list1, List<T> list2) {
1111         List<T> list = new ArrayList<>();
1112         for (T t : list1) {
1113             if(list2.contains(t)) {
1114                 list.add(t);
1115             }
1116         }
1117         return list;
1118     }
1119
1120     public static void addTransportZoneMembership(List<TzMembership> zones, String zoneName) {
1121         zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());
1122     }
1123
1124     public static  List<TzMembership> createTransportZoneMembership(String zoneName) {
1125         List<TzMembership> zones = new ArrayList<>();
1126         zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());
1127         return zones;
1128     }
1129
1130 }