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.FlowEntity;
38 import org.opendaylight.genius.mdsalutil.InstructionInfo;
39 import org.opendaylight.genius.mdsalutil.InstructionType;
40 import org.opendaylight.genius.mdsalutil.MDSALUtil;
41 import org.opendaylight.genius.mdsalutil.MatchFieldType;
42 import org.opendaylight.genius.mdsalutil.MatchInfo;
43 import org.opendaylight.genius.mdsalutil.NwConstants;
44 import org.opendaylight.genius.mdsalutil.actions.ActionPuntToController;
45 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.Tunnel;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlan;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlanBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnelBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefsBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelMonitoringTypeBase;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeGre;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeMplsOverGre;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifier;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierBuilder;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierKey;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorInterval;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorIntervalBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorParams;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorParamsBuilder;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.VtepConfigSchemas;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.VtepIpPools;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchema;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaKey;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIds;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsKey;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPool;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPoolKey;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpoints;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpointsBuilder;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelList;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfo;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoBuilder;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoKey;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPoints;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsBuilder;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsKey;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.tunnel.end.points.TzMembership;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.tunnel.end.points.TzMembershipBuilder;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelBuilder;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnel;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelBuilder;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelKey;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.StateTunnelListKey;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.DcGatewayIpList;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.TransportZones;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.dc.gateway.ip.list.DcGatewayIp;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZone;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZoneKey;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.Subnets;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.subnets.Vteps;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelMonitoringTypeBfd;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
117 import org.opendaylight.yangtools.yang.binding.DataObject;
118 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
119 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
120 import org.opendaylight.yangtools.yang.common.RpcResult;
121 import org.opendaylight.genius.utils.cache.DataStoreCache;
122 import org.slf4j.Logger;
123 import org.slf4j.LoggerFactory;
125 public class ItmUtils {
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();
133 private static final Logger LOG = LoggerFactory.getLogger(ItmUtils.class);
135 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
137 public void onSuccess(Void result) {
138 LOG.debug("Success in Datastore write operation");
142 public void onFailure(Throwable error) {
143 LOG.error("Error in Datastore write operation", error);
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);
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);
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);
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);
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);
183 Futures.addCallback(tx.submit(), callback);
187 public static String getInterfaceName(final BigInteger datapathid, final String portName, final Integer vlanId) {
188 return String.format("%s:%s:%s", datapathid, portName, vlanId);
191 public static BigInteger getDpnIdFromInterfaceName(String interfaceName) {
192 String[] dpnStr = interfaceName.split(":");
193 BigInteger dpnId = new BigInteger(dpnStr[0]);
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;
203 tunnelTypeStr = ITMConstants.TUNNEL_TYPE_VXLAN;
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;
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;
217 tunnelTypeStr = ITMConstants.TUNNEL_TYPE_VXLAN;
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) ;
224 public static InetAddress getInetAddressFromIpAddress(IpAddress ip) {
225 return InetAddresses.forString(ip.getIpv4Address().getValue());
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();
236 public static DPNTEPsInfo createDPNTepInfo(BigInteger dpId, List<TunnelEndPoints> endpoints) {
238 return new DPNTEPsInfoBuilder().setKey(new DPNTEPsInfoKey(dpId)).setTunnelEndPoints(endpoints).build();
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();
252 public static DpnEndpoints createDpnEndpoints(List<DPNTEPsInfo> dpnTepInfo) {
253 return new DpnEndpointsBuilder().setDPNTEPsInfo(dpnTepInfo).build();
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();
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;
275 IfL2vlan l2vlan = new IfL2vlanBuilder().setVlanId(new VlanId(vlanId)).build();
276 builder.addAugmentation(IfL2vlan.class, l2vlan);
278 LOG.debug("buildTunnelInterface: monitorProtocol = {} and monitorInterval = {}",monitorProtocol.getName(),monitorInterval);
281 if(monitorInterval != null) {
282 monitoringInterval = monitorInterval.longValue();
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)
290 builder.addAugmentation(IfTunnel.class, tunnel);
291 return builder.build();
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(
303 setNodeId(node_id).build();
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();
313 if(monitor_enabled!=null ) {
314 monitoringEnabled = monitor_enabled;
316 if(monitorProtocol!=null) {
317 monitoringProtocol = monitorProtocol;
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();
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();
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();
348 public static List<DPNTEPsInfo> getTunnelMeshInfo(DataBroker dataBroker) {
349 List<DPNTEPsInfo> dpnTEPs= null ;
351 // Read the Mesh Information from Cache if not read from the DS
352 dpnTEPs = getTunnelMeshInfo() ;
353 if( dpnTEPs != null ) {
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() );
366 LOG.debug( "No Dpn information in CONFIGURATION datastore " );
371 // Reading the Mesh Information from Cache
372 public static List<DPNTEPsInfo> getTunnelMeshInfo(){
373 List<DPNTEPsInfo> dpnTepsInfo = null ;
374 List<Object> values = null ;
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) ;
386 public static int getUniqueId(IdManagerService idManager, String idKey) {
387 AllocateIdInput getIdInput = new AllocateIdInputBuilder()
388 .setPoolName(ITMConstants.ITM_IDPOOL_NAME)
389 .setIdKey(idKey).build();
392 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
393 RpcResult<AllocateIdOutput> rpcResult = result.get();
394 if(rpcResult.isSuccessful()) {
395 return rpcResult.getResult().getIdValue().intValue();
397 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
399 } catch (InterruptedException | ExecutionException e) {
400 LOG.warn("Exception when getting Unique Id",e);
405 public static String getUniqueIdString(String idKey) {
406 return UUID.nameUUIDFromBytes(idKey.getBytes()).toString().substring(0, 12).replace("-", "");
409 public static void releaseId(IdManagerService idManager, String idKey) {
410 ReleaseIdInput idInput =
411 new ReleaseIdInputBuilder().setPoolName(ITMConstants.ITM_IDPOOL_NAME).setIdKey(idKey).build();
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());
418 } catch (InterruptedException | ExecutionException e) {
419 LOG.warn("Exception when getting Unique Id for key {}", idKey, e);
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) ;
438 public static void setUpOrRemoveTerminatingServiceTable(BigInteger dpnId, IMdsalApiManager mdsalManager, boolean addFlag) {
439 String logmsg = addFlag ? "Installing" : "Removing";
440 LOG.trace( logmsg + " PUNT to Controller flow in DPN {} ", dpnId );
441 List<ActionInfo> listActionInfo = new ArrayList<>();
442 listActionInfo.add(new ActionPuntToController());
445 List<MatchInfo> mkMatches = new ArrayList<>();
447 mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {
448 BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID) }));
450 List<InstructionInfo> mkInstructions = new ArrayList<>();
451 mkInstructions.add(new InstructionInfo(InstructionType.apply_actions,
454 FlowEntity terminatingServiceTableFlowEntity = MDSALUtil
457 NwConstants.INTERNAL_TUNNEL_TABLE,
458 getFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE,
459 ITMConstants.LLDP_SERVICE_ID), 5, String.format("%s:%d","ITM Flow Entry ",ITMConstants.LLDP_SERVICE_ID),
460 0, 0, ITMConstants.COOKIE_ITM
461 .add(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)),
462 mkMatches, mkInstructions);
464 mdsalManager.installFlow(terminatingServiceTableFlowEntity);
466 mdsalManager.removeFlow(terminatingServiceTableFlowEntity);
468 } catch (Exception e) {
469 LOG.error("Error while setting up Table 36 for {}", dpnId, e);
473 private static String getFlowRef(long termSvcTable, int svcId) {
474 return String.valueOf(termSvcTable) + svcId;
476 public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier(String schemaName) {
477 return InstanceIdentifier.builder(VtepConfigSchemas.class)
478 .child(VtepConfigSchema.class, new VtepConfigSchemaKey(schemaName)).build();
481 public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier() {
482 return InstanceIdentifier.builder(VtepConfigSchemas.class).child(VtepConfigSchema.class).build();
484 public static InstanceIdentifier<VtepConfigSchemas> getVtepConfigSchemasIdentifier() {
485 return InstanceIdentifier.builder(VtepConfigSchemas.class).build();
487 public static InstanceIdentifier<VtepIpPool> getVtepIpPoolIdentifier(String subnetCidr) {
488 return InstanceIdentifier.builder(VtepIpPools.class).child(VtepIpPool.class, new VtepIpPoolKey(subnetCidr))
491 public static VtepConfigSchema validateForAddVtepConfigSchema(VtepConfigSchema schema,
492 List<VtepConfigSchema> existingSchemas) {
493 VtepConfigSchema validSchema = validateVtepConfigSchema(schema);
494 for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
495 if (!StringUtils.equalsIgnoreCase(schema.getSchemaName(), existingSchema.getSchemaName())
496 && schema.getSubnet().equals(existingSchema.getSubnet())) {
497 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
498 Preconditions.checkArgument(false, "VTEP schema with subnet [" + subnetCidr +
499 "] already exists. Multiple VTEP schemas with same subnet is not allowed.");
502 if (isNotEmpty(getDpnIdList(validSchema.getDpnIds()))) {
503 String tzone = validSchema.getTransportZoneName();
504 List<BigInteger> lstDpns = getConflictingDpnsAlreadyConfiguredWithTz(validSchema.getSchemaName(), tzone,
505 getDpnIdList(validSchema.getDpnIds()), existingSchemas);
506 if (!lstDpns.isEmpty()) {
507 Preconditions.checkArgument(false,
508 "DPN's " + lstDpns + " already configured for transport zone " +
509 tzone + ". Only one end point per transport Zone per Dpn is allowed.");
511 if (schema.getTunnelType().equals(TunnelTypeGre.class)){
512 validateForSingleGreTep(validSchema.getSchemaName(), getDpnIdList(validSchema.getDpnIds()), existingSchemas);
517 private static void validateForSingleGreTep(String schemaName, List<BigInteger> lstDpnsForAdd,
518 List<VtepConfigSchema> existingSchemas) {
519 for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
520 if (TunnelTypeGre.class.equals(existingSchema.getTunnelType())
521 && !StringUtils.equalsIgnoreCase(schemaName, existingSchema.getSchemaName())) {
522 List<BigInteger> lstConflictingDpns = new ArrayList<>(getDpnIdList(existingSchema.getDpnIds()));
523 lstConflictingDpns.retainAll(emptyIfNull(lstDpnsForAdd));
524 if (!lstConflictingDpns.isEmpty()) {
525 String errMsg = "DPN's " + lstConflictingDpns +
526 " already configured with GRE TEP. Mutiple GRE TEP's on a single DPN are not allowed.";
527 Preconditions.checkArgument(false, errMsg);
532 public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
533 Preconditions.checkNotNull(schema);
534 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
535 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
536 Preconditions.checkArgument(schema.getVlanId() >= 0 && schema.getVlanId() < 4095,
537 "Invalid VLAN ID, range (0-4094)");
538 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
539 Preconditions.checkNotNull(schema.getSubnet());
540 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
541 SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
542 IpAddress gatewayIp = schema.getGatewayIp();
543 if (gatewayIp != null) {
544 String strGatewayIp = String.valueOf(gatewayIp.getValue());
545 if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS) && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
546 Preconditions.checkArgument(false, "Gateway IP address " + strGatewayIp +
547 " is not in subnet range " + subnetCidr);
550 ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
551 return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
553 public static String validateTunnelType(String tunnelType) {
554 if (tunnelType == null) {
555 tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
557 tunnelType = StringUtils.upperCase(tunnelType);
558 String error = "Invalid tunnel type. Valid values: " +
559 ITMConstants.TUNNEL_TYPE_VXLAN + " | " + ITMConstants.TUNNEL_TYPE_GRE;
560 Preconditions.checkArgument(ITMConstants.TUNNEL_TYPE_VXLAN.equals(tunnelType)
561 || ITMConstants.TUNNEL_TYPE_GRE.equals(tunnelType), error);
565 private static List<BigInteger> getConflictingDpnsAlreadyConfiguredWithTz(String schemaName, String tzone,
566 List<BigInteger> lstDpns, List<VtepConfigSchema> existingSchemas) {
567 List<BigInteger> lstConflictingDpns = new ArrayList<>();
568 for (VtepConfigSchema schema : emptyIfNull(existingSchemas)) {
569 if (!StringUtils.equalsIgnoreCase(schemaName, schema.getSchemaName())
570 && StringUtils.equals(schema.getTransportZoneName(), tzone)) {
571 lstConflictingDpns = new ArrayList<>(getDpnIdList(schema.getDpnIds()));
572 lstConflictingDpns.retainAll(lstDpns);
573 if (!lstConflictingDpns.isEmpty()) {
578 return lstConflictingDpns;
580 public static VtepConfigSchema constructVtepConfigSchema(String schemaName, String portName, Integer vlanId,
581 String subnetMask, String gatewayIp, String transportZone,String tunnelType, List<BigInteger> dpnIds,
582 String excludeIpFilter) {
583 IpAddress gatewayIpObj = StringUtils.isBlank(gatewayIp) ? null : new IpAddress(gatewayIp.toCharArray());
584 IpPrefix subnet = StringUtils.isBlank(subnetMask) ? null : new IpPrefix(subnetMask.toCharArray());
585 Class<? extends TunnelTypeBase> tunType ;
586 if( tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN)) {
587 tunType = TunnelTypeVxlan.class ;
589 tunType = TunnelTypeGre.class ;
591 VtepConfigSchemaBuilder schemaBuilder = new VtepConfigSchemaBuilder().setSchemaName(schemaName)
592 .setPortName(portName).setVlanId(vlanId).setSubnet(subnet).setGatewayIp(gatewayIpObj)
593 .setTransportZoneName(transportZone).setTunnelType(tunType).setDpnIds(getDpnIdsListFromBigInt(dpnIds))
594 .setExcludeIpFilter(excludeIpFilter);
595 return schemaBuilder.build();
597 public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
598 final List<IpAddress> lstIpAddress = new ArrayList<>();
599 if (StringUtils.isBlank(excludeIpFilter)) {
602 final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
603 for (String ip : arrIps) {
604 if (StringUtils.countMatches(ip, "-") == 1) {
605 final String[] arrIpRange = StringUtils.split(ip, '-');
606 String strStartIp = StringUtils.trim(arrIpRange[0]);
607 String strEndIp = StringUtils.trim(arrIpRange[1]);
608 Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
609 "Invalid exclude IP filter: invalid IP address value " + strStartIp);
610 Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
611 "Invalid exclude IP filter: invalid IP address value " + strEndIp);
612 Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
613 "Invalid exclude IP filter: IP address [" + strStartIp +
614 "] not in subnet range " + subnetInfo.getCidrSignature());
615 Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
616 "Invalid exclude IP filter: IP address [" + strEndIp +
617 "] not in subnet range " + subnetInfo.getCidrSignature());
618 int startIp = subnetInfo.asInteger(strStartIp);
619 int endIp = subnetInfo.asInteger(strEndIp);
621 Preconditions.checkArgument(startIp < endIp,
622 "Invalid exclude IP filter: Invalid range [" + ip + "] ");
623 for (int i = startIp; i <= endIp; i++) {
624 String ipAddress = ipFormat(toIpArray(i));
625 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
628 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
633 private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
635 String ip = StringUtils.trim(ipAddress);
636 Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
637 "Invalid exclude IP filter: invalid IP address value " + ip);
638 Preconditions.checkArgument(subnetInfo.isInRange(ip),
639 "Invalid exclude IP filter: IP address [" + ip + "] not in subnet range " +
640 subnetInfo.getCidrSignature());
641 lstIpAddress.add(new IpAddress(ip.toCharArray()));
643 private static int[] toIpArray(int val) {
644 int[] ret = new int[4];
645 for (int j = 3; j >= 0; --j) {
646 ret[j] |= val >>> 8 * (3 - j) & 0xff;
650 private static String ipFormat(int[] octets) {
651 StringBuilder str = new StringBuilder();
652 for (int i = 0; i < octets.length; ++i) {
653 str.append(octets[i]);
654 if (i != octets.length - 1) {
658 return str.toString();
660 public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd,
661 List<BigInteger> lstDpnsForDelete, IITMProvider itmProvider) {
662 Preconditions.checkArgument(StringUtils.isNotBlank(schemaName));
663 if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty())
664 && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) {
665 Preconditions.checkArgument(false,
666 "DPN ID list for add | delete is null or empty in schema " + schemaName);
668 VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName);
669 if (schema == null) {
670 Preconditions.checkArgument(false, "Specified VTEP Schema [" + schemaName +
671 "] doesn't exists!");
673 List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds());
674 if (isNotEmpty(lstDpnsForAdd)) {
675 // if (isNotEmpty(existingDpnIds)) {
676 List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds);
677 lstAlreadyExistingDpns.retainAll(lstDpnsForAdd);
678 Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(),
679 "DPN ID's " + lstAlreadyExistingDpns +
680 " already exists in VTEP schema [" + schemaName + "]");
682 if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
683 validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd, itmProvider.getAllVtepConfigSchemas());
686 if (isNotEmpty(lstDpnsForDelete)) {
687 if (existingDpnIds == null || existingDpnIds.isEmpty()) {
688 String builder = "DPN ID's " + lstDpnsForDelete +
689 " specified for delete from VTEP schema [" + schemaName +
690 "] are not configured in the schema.";
691 Preconditions.checkArgument(false, builder);
692 } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) {
693 List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete);
694 lstConflictingDpns.removeAll(existingDpnIds);
695 String builder = "DPN ID's " + lstConflictingDpns +
696 " specified for delete from VTEP schema [" + schemaName +
697 "] are not configured in the schema.";
698 Preconditions.checkArgument(false, builder);
703 public static String getSubnetCidrAsString(IpPrefix subnet) {
704 return subnet == null ? StringUtils.EMPTY : String.valueOf(subnet.getValue());
706 public static <T> List<T> emptyIfNull(List<T> list) {
707 return list == null ? Collections.emptyList() : list;
709 public static <T> boolean isEmpty(Collection<T> collection) {
710 return collection == null || collection.isEmpty();
712 public static <T> boolean isNotEmpty(Collection<T> collection) {
713 return !isEmpty(collection);
715 public static HwVtep createHwVtepObject(String topo_id, String node_id, IpAddress ipAddress, IpPrefix ipPrefix, IpAddress gatewayIP, int vlanID, Class<? extends TunnelTypeBase> tunnel_type, TransportZone transportZone) {
716 HwVtep hwVtep = new HwVtep();
717 hwVtep.setGatewayIP(gatewayIP);
718 hwVtep.setHwIp(ipAddress);
719 hwVtep.setIpPrefix(ipPrefix);
720 hwVtep.setNode_id(node_id);
721 hwVtep.setTopo_id(topo_id);
722 hwVtep.setTransportZone(transportZone.getZoneName());
723 hwVtep.setTunnel_type(tunnel_type);
724 hwVtep.setVlanID(vlanID);
728 public static String getHwParentIf(String topo_id, String srcNodeid) {
729 return String.format("%s:%s", topo_id, srcNodeid);
732 public static <T extends DataObject> void syncWrite(LogicalDatastoreType datastoreType,
733 InstanceIdentifier<T> path, T data, DataBroker broker) {
734 WriteTransaction tx = broker.newWriteOnlyTransaction();
735 tx.put(datastoreType, path, data, true);
736 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
739 } catch (InterruptedException | ExecutionException e) {
740 LOG.error("ITMUtils:SyncWrite , Error writing to datastore (path, data) : ({}, {})", path, data);
741 throw new RuntimeException(e.getMessage());
745 public static List<BigInteger> getDpnIdList( List<DpnIds> dpnIds ) {
746 List<BigInteger> dpnList = new ArrayList<>() ;
747 for( DpnIds dpn : dpnIds) {
748 dpnList.add(dpn.getDPN()) ;
753 public static List<DpnIds> getDpnIdsListFromBigInt( List<BigInteger> dpnIds) {
754 List<DpnIds> dpnIdList = new ArrayList<>() ;
755 DpnIdsBuilder builder = new DpnIdsBuilder() ;
756 for( BigInteger dpnId : dpnIds) {
757 dpnIdList.add(builder.setKey(new DpnIdsKey(dpnId)).setDPN(dpnId).build() );
762 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
763 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder =
764 InstanceIdentifier.builder(InterfacesState.class)
765 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.class,
766 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
768 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> id = idBuilder.build();
771 public static Boolean readMonitoringStateFromCache(DataBroker dataBroker) {
772 InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
773 TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
774 if(tunnelMonitorParams!=null) {
775 return tunnelMonitorParams.isEnabled();
777 return ITMConstants.DEFAULT_MONITOR_ENABLED;
781 public static Integer readMonitorIntervalfromCache(DataBroker dataBroker) {
782 InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.create(TunnelMonitorInterval.class);
783 TunnelMonitorInterval tunnelMonitorIOptional = (TunnelMonitorInterval)DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"Interval",dataBroker,true);
784 if(tunnelMonitorIOptional!=null) {
785 return tunnelMonitorIOptional.getInterval();
791 public static Integer determineMonitorInterval(DataBroker dataBroker) {
792 Integer monitorInterval = ItmUtils.readMonitorIntervalfromCache(dataBroker);
793 LOG.debug("determineMonitorInterval: monitorInterval from DS = {}", monitorInterval);
794 if(monitorInterval==null){
795 Class<? extends TunnelMonitoringTypeBase> monitorProtocol = determineMonitorProtocol(dataBroker);
796 if(monitorProtocol.isAssignableFrom(TunnelMonitoringTypeBfd.class)) {
797 monitorInterval = ITMConstants.BFD_DEFAULT_MONITOR_INTERVAL;
799 monitorInterval = ITMConstants.DEFAULT_MONITOR_INTERVAL;
802 LOG.debug("determineMonitorInterval: monitorInterval = {}", monitorInterval);
803 InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.builder(TunnelMonitorInterval.class).build();
804 TunnelMonitorInterval intervalBuilder = new TunnelMonitorIntervalBuilder().setInterval(monitorInterval).build();
805 ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, intervalBuilder, dataBroker, ItmUtils.DEFAULT_CALLBACK);
806 return monitorInterval;
809 public static List<String> getInternalTunnelInterfaces(DataBroker dataBroker){
810 List<String> tunnelList = new ArrayList<>();
811 Collection<String> internalInterfaces = itmCache.getAllInternalInterfaces();
812 if(internalInterfaces == null) {
813 updateTunnelsCache(dataBroker);
814 internalInterfaces = itmCache.getAllInternalInterfaces();
816 LOG.debug("ItmUtils.getTunnelList Cache Internal Interfaces size: {} ", internalInterfaces.size());
817 if(internalInterfaces!=null) {
818 tunnelList.addAll(internalInterfaces);
820 LOG.trace("ItmUtils.getTunnelList Internal: {}", tunnelList);
824 public static List<String> getTunnelsofTzone(List<HwVtep> hwVteps, String tzone, DataBroker dataBroker, Boolean hwVtepsExist) {
826 List<String> tunnels = new ArrayList<>();
827 InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
828 child(TransportZone.class, new TransportZoneKey(tzone)).build();
829 Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
830 if (tZoneOptional.isPresent()) {
831 TransportZone transportZone = tZoneOptional.get();
832 Class<? extends TunnelTypeBase> tunType = transportZone.getTunnelType();
833 if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
834 for (Subnets sub : transportZone.getSubnets()) {
835 if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
836 for (Vteps vtepLocal : sub.getVteps()) {
837 for (Vteps vtepRemote : sub.getVteps()) {
838 if (!vtepLocal.equals(vtepRemote)) {
839 InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(), tunType);
840 InstanceIdentifier<InternalTunnel> intIID =
841 InstanceIdentifier.builder(TunnelList.class).
842 child(InternalTunnel.class, key).build();
843 Optional<InternalTunnel> TunnelsOptional =
844 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
845 if (TunnelsOptional.isPresent()) {
846 String tunnelInterfaceName = TunnelsOptional.get().getTunnelInterfaceName();
847 LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
848 tunnels.add(tunnelInterfaceName);
852 if(hwVteps!= null && !hwVteps.isEmpty()) {
853 for (HwVtep hwVtep : hwVteps) {
854 tunnels.add(getExtTunnel(hwVtep.getNode_id(), vtepLocal.getDpnId().toString(),
855 tunType, dataBroker));
856 tunnels.add(getExtTunnel(vtepLocal.getDpnId().toString(), hwVtep.getNode_id(),
857 tunType, dataBroker));
865 for (HwVtep hwVtep : hwVteps) {
866 for (HwVtep hwVtepOther : hwVteps) {
867 if (!hwVtep.getHwIp().equals(hwVtepOther.getHwIp())) {
868 tunnels.add(getExtTunnel(hwVtep.getNode_id(), hwVtepOther.getNode_id(), tunType, dataBroker));
869 tunnels.add(getExtTunnel(hwVtepOther.getNode_id(), hwVtep.getNode_id(), tunType, dataBroker));
878 public static List<String> getInternalTunnelsofTzone(String tzone, DataBroker dataBroker) {
879 List<String> tunnels = new ArrayList<>();
880 LOG.trace("Getting internal tunnels of {}",tzone);
881 InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
882 child(TransportZone.class, new TransportZoneKey(tzone)).build();
883 Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
884 if (tZoneOptional.isPresent()) {
885 TransportZone transportZone = tZoneOptional.get();
886 if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
887 for (Subnets sub : transportZone.getSubnets()) {
888 if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
889 for (Vteps vtepLocal : sub.getVteps()) {
890 for (Vteps vtepRemote : sub.getVteps()) {
891 if (!vtepLocal.equals(vtepRemote)) {
892 InternalTunnelKey key =
893 new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(),
894 transportZone.getTunnelType());
895 InstanceIdentifier<InternalTunnel> intIID =
896 InstanceIdentifier.builder(TunnelList.class).
897 child(InternalTunnel.class, key).build();
898 Optional<InternalTunnel> tunnelsOptional =
899 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
900 if (tunnelsOptional.isPresent()) {
901 String tunnelInterfaceName = tunnelsOptional.get().getTunnelInterfaceName();
902 LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
903 tunnels.add(tunnelInterfaceName);
915 private static String getExtTunnel(String node_id, String dpId,Class<? extends TunnelTypeBase> tunType, DataBroker dataBroker) {
916 LOG.trace("getting ext tunnel for {} and dpId {}",node_id,dpId);
917 ExternalTunnelKey key = getExternalTunnelKey(dpId, node_id, tunType);
918 InstanceIdentifier<ExternalTunnel> intIID = InstanceIdentifier.builder(ExternalTunnelList.class).
919 child(ExternalTunnel.class, key).build();
920 Optional<ExternalTunnel> tunnelsOptional =
921 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
922 if (tunnelsOptional.isPresent()) {
923 String tunnelInterfaceName = tunnelsOptional.get().getTunnelInterfaceName();
924 LOG.trace("ext tunnel returned {} ", tunnelInterfaceName);
925 return tunnelInterfaceName;
929 public static ExternalTunnelKey getExternalTunnelKey(String dst , String src, Class<? extends TunnelTypeBase> tunType) {
930 if (src.indexOf("physicalswitch") > 0) {
931 src = src.substring(0, src.indexOf("physicalswitch") - 1);
933 if (dst.indexOf("physicalswitch") > 0) {
934 dst = dst.substring(0, dst.indexOf("physicalswitch") - 1);
936 return new ExternalTunnelKey(dst, src, tunType);
939 public static List<TunnelEndPoints> getTEPsForDpn( BigInteger srcDpn, List<DPNTEPsInfo> dpnList) {
940 for (DPNTEPsInfo dpn : dpnList) {
941 if( dpn.getDPNID().equals(srcDpn)) {
942 return dpn.getTunnelEndPoints() ;
947 public static TunnelList getAllInternalTunnels(DataBroker broker) {
948 InstanceIdentifier<TunnelList> tunnelListInstanceIdentifier = InstanceIdentifier.builder(TunnelList.class).build();
949 return read(LogicalDatastoreType.CONFIGURATION, tunnelListInstanceIdentifier, broker).orNull();
951 public static InternalTunnel getInternalTunnel(String interfaceName, DataBroker broker) {
952 InternalTunnel internalTunnel = null;
953 TunnelList tunnelList = getAllInternalTunnels(broker);
954 if (tunnelList != null && tunnelList.getInternalTunnel() != null) {
955 List<InternalTunnel> internalTunnels = tunnelList.getInternalTunnel();
956 for (InternalTunnel tunnel : internalTunnels) {
957 if (tunnel.getTunnelInterfaceName().equalsIgnoreCase(interfaceName)) {
958 internalTunnel = tunnel;
963 return internalTunnel;
965 public static ExternalTunnel getExternalTunnel(String interfaceName, DataBroker broker) {
966 ExternalTunnel externalTunnel = null;
967 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker);
968 for (ExternalTunnel tunnel : externalTunnels) {
969 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
970 externalTunnel = tunnel;
974 return externalTunnel;
976 public static List<ExternalTunnel> getAllExternalTunnels(DataBroker broker) {
977 List<ExternalTunnel> result = null;
978 InstanceIdentifier<ExternalTunnelList> id = InstanceIdentifier.builder(ExternalTunnelList.class).build();
979 Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, id, broker);
980 if (tunnelList.isPresent()) {
981 result = tunnelList.get().getExternalTunnel();
983 if (result == null) {
984 result = Collections.emptyList();
988 public static String convertTunnelTypetoString(Class<? extends TunnelTypeBase> tunType ) {
989 String tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
990 if( tunType.equals(TunnelTypeVxlan.class)) {
991 tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN ;
992 } else if( tunType.equals(TunnelTypeGre.class) ) {
993 tunnelType = ITMConstants.TUNNEL_TYPE_GRE ;
994 } else if (tunnelType.equals(TunnelTypeMplsOverGre.class)) {
995 tunnelType = ITMConstants.TUNNEL_TYPE_MPLSoGRE;
1001 public static boolean isItmIfType(Class<? extends InterfaceType> ifType) {
1002 return ifType != null && ifType.isAssignableFrom(Tunnel.class);
1005 public static StateTunnelListKey getTunnelStateKey( org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface iface) {
1006 StateTunnelListKey key = null;
1007 if(isItmIfType(iface.getType())) {
1008 key = new StateTunnelListKey(iface.getName());
1013 public static void updateTunnelsCache(DataBroker broker) {
1014 List<InternalTunnel> internalTunnels = getAllInternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
1015 for (InternalTunnel tunnel : internalTunnels) {
1016 itmCache.addInternalTunnel(tunnel);
1018 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
1019 for (ExternalTunnel tunnel : externalTunnels) {
1020 itmCache.addExternalTunnel(tunnel);
1024 public static List<ExternalTunnel> getAllExternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
1025 List<ExternalTunnel> result = null;
1026 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1027 Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1028 if (tunnelList.isPresent()) {
1029 result = tunnelList.get().getExternalTunnel();
1031 if (result == null) {
1032 result = Collections.emptyList();
1037 public static List<InternalTunnel> getAllInternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
1038 List<InternalTunnel> result = null;
1039 InstanceIdentifier<TunnelList> iid = InstanceIdentifier.builder(TunnelList.class).build();
1040 Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1041 if (tunnelList.isPresent()) {
1042 result = tunnelList.get().getInternalTunnel();
1044 if (result == null) {
1045 result = Collections.emptyList();
1050 public static Interface getInterface(
1051 String name, DataBroker broker) {
1052 Interface result = itmCache.getInterface(name);
1053 if (result == null) {
1054 InstanceIdentifier<Interface> iid =
1055 InstanceIdentifier.builder(Interfaces.class)
1056 .child(Interface.class, new InterfaceKey(name)).build();
1057 Optional<Interface> optInterface = read(LogicalDatastoreType.CONFIGURATION, iid, broker);
1058 if (optInterface.isPresent()) {
1059 result = optInterface.get();
1060 itmCache.addInterface(result);
1066 public static Class<? extends TunnelMonitoringTypeBase> readMonitoringProtocolFromCache(DataBroker dataBroker) {
1067 InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
1068 TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
1069 if(tunnelMonitorParams!=null) {
1070 return tunnelMonitorParams.getMonitorProtocol();
1075 public static Class<? extends TunnelMonitoringTypeBase> determineMonitorProtocol(DataBroker dataBroker) {
1076 Class<? extends TunnelMonitoringTypeBase> monitoringProtocol = ItmUtils.readMonitoringProtocolFromCache(dataBroker);
1077 LOG.debug("determineMonitorProtocol: monitorProtocol from DS = {}", monitoringProtocol);
1078 if(monitoringProtocol==null) {
1079 monitoringProtocol = ITMConstants.DEFAULT_MONITOR_PROTOCOL;
1081 LOG.debug("determineMonitorProtocol: monitorProtocol = {}", monitoringProtocol);
1082 Boolean monitorState = ItmUtils.readMonitoringStateFromCache(dataBroker);
1083 if(monitorState==null) {
1084 monitorState = true;
1086 LOG.debug("determineMonitorProtocol: monitorState = {}", monitorState);
1087 InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.builder(TunnelMonitorParams.class).build();
1088 TunnelMonitorParams protocolBuilder = new TunnelMonitorParamsBuilder().setEnabled(monitorState).setMonitorProtocol(monitoringProtocol).build();
1089 ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, protocolBuilder, dataBroker, ItmUtils.DEFAULT_CALLBACK);
1090 return monitoringProtocol;
1093 public static List<DcGatewayIp> getDcGatewayIpList(DataBroker broker){
1094 InstanceIdentifier<DcGatewayIpList> dcGatewayIpListid = InstanceIdentifier.builder(DcGatewayIpList.class).build();
1095 Optional<DcGatewayIpList> dcGatewayIpListConfig = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, dcGatewayIpListid, broker);
1096 if(dcGatewayIpListConfig.isPresent()){
1097 DcGatewayIpList containerList = dcGatewayIpListConfig.get();
1098 if(containerList != null){
1099 return containerList.getDcGatewayIp();
1105 public static boolean falseIfNull(Boolean value) {
1106 return value == null ? false : value;
1109 public static <T> List<T> getIntersection(List<T> list1, List<T> list2) {
1110 List<T> list = new ArrayList<>();
1112 if(list2.contains(t)) {
1119 public static void addTransportZoneMembership(List<TzMembership> zones, String zoneName) {
1120 zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());
1123 public static List<TzMembership> createTransportZoneMembership(String zoneName) {
1124 List<TzMembership> zones = new ArrayList<>();
1125 zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());