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