2 * Copyright © 2016, 2017 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.MDSALUtil;
40 import org.opendaylight.genius.mdsalutil.MatchFieldType;
41 import org.opendaylight.genius.mdsalutil.MatchInfo;
42 import org.opendaylight.genius.mdsalutil.NwConstants;
43 import org.opendaylight.genius.mdsalutil.actions.ActionPuntToController;
44 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
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 InstructionApplyActions(listActionInfo));
453 FlowEntity terminatingServiceTableFlowEntity = MDSALUtil
456 NwConstants.INTERNAL_TUNNEL_TABLE,
457 getFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE,
458 ITMConstants.LLDP_SERVICE_ID), 5, String.format("%s:%d","ITM Flow Entry ",ITMConstants.LLDP_SERVICE_ID),
459 0, 0, ITMConstants.COOKIE_ITM
460 .add(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)),
461 mkMatches, mkInstructions);
463 mdsalManager.installFlow(terminatingServiceTableFlowEntity);
465 mdsalManager.removeFlow(terminatingServiceTableFlowEntity);
467 } catch (Exception e) {
468 LOG.error("Error while setting up Table 36 for {}", dpnId, e);
472 private static String getFlowRef(long termSvcTable, int svcId) {
473 return String.valueOf(termSvcTable) + svcId;
475 public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier(String schemaName) {
476 return InstanceIdentifier.builder(VtepConfigSchemas.class)
477 .child(VtepConfigSchema.class, new VtepConfigSchemaKey(schemaName)).build();
480 public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier() {
481 return InstanceIdentifier.builder(VtepConfigSchemas.class).child(VtepConfigSchema.class).build();
483 public static InstanceIdentifier<VtepConfigSchemas> getVtepConfigSchemasIdentifier() {
484 return InstanceIdentifier.builder(VtepConfigSchemas.class).build();
486 public static InstanceIdentifier<VtepIpPool> getVtepIpPoolIdentifier(String subnetCidr) {
487 return InstanceIdentifier.builder(VtepIpPools.class).child(VtepIpPool.class, new VtepIpPoolKey(subnetCidr))
490 public static VtepConfigSchema validateForAddVtepConfigSchema(VtepConfigSchema schema,
491 List<VtepConfigSchema> existingSchemas) {
492 VtepConfigSchema validSchema = validateVtepConfigSchema(schema);
493 for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
494 if (!StringUtils.equalsIgnoreCase(schema.getSchemaName(), existingSchema.getSchemaName())
495 && schema.getSubnet().equals(existingSchema.getSubnet())) {
496 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
497 Preconditions.checkArgument(false, "VTEP schema with subnet [" + subnetCidr +
498 "] already exists. Multiple VTEP schemas with same subnet is not allowed.");
501 if (isNotEmpty(getDpnIdList(validSchema.getDpnIds()))) {
502 String tzone = validSchema.getTransportZoneName();
503 List<BigInteger> lstDpns = getConflictingDpnsAlreadyConfiguredWithTz(validSchema.getSchemaName(), tzone,
504 getDpnIdList(validSchema.getDpnIds()), existingSchemas);
505 if (!lstDpns.isEmpty()) {
506 Preconditions.checkArgument(false,
507 "DPN's " + lstDpns + " already configured for transport zone " +
508 tzone + ". Only one end point per transport Zone per Dpn is allowed.");
510 if (schema.getTunnelType().equals(TunnelTypeGre.class)){
511 validateForSingleGreTep(validSchema.getSchemaName(), getDpnIdList(validSchema.getDpnIds()), existingSchemas);
516 private static void validateForSingleGreTep(String schemaName, List<BigInteger> lstDpnsForAdd,
517 List<VtepConfigSchema> existingSchemas) {
518 for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
519 if (TunnelTypeGre.class.equals(existingSchema.getTunnelType())
520 && !StringUtils.equalsIgnoreCase(schemaName, existingSchema.getSchemaName())) {
521 List<BigInteger> lstConflictingDpns = new ArrayList<>(getDpnIdList(existingSchema.getDpnIds()));
522 lstConflictingDpns.retainAll(emptyIfNull(lstDpnsForAdd));
523 if (!lstConflictingDpns.isEmpty()) {
524 String errMsg = "DPN's " + lstConflictingDpns +
525 " already configured with GRE TEP. Mutiple GRE TEP's on a single DPN are not allowed.";
526 Preconditions.checkArgument(false, errMsg);
531 public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
532 Preconditions.checkNotNull(schema);
533 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
534 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
535 Preconditions.checkArgument(schema.getVlanId() >= 0 && schema.getVlanId() < 4095,
536 "Invalid VLAN ID, range (0-4094)");
537 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
538 Preconditions.checkNotNull(schema.getSubnet());
539 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
540 SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
541 IpAddress gatewayIp = schema.getGatewayIp();
542 if (gatewayIp != null) {
543 String strGatewayIp = String.valueOf(gatewayIp.getValue());
544 if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS) && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
545 Preconditions.checkArgument(false, "Gateway IP address " + strGatewayIp +
546 " is not in subnet range " + subnetCidr);
549 ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
550 return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
552 public static String validateTunnelType(String tunnelType) {
553 if (tunnelType == null) {
554 tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
556 tunnelType = StringUtils.upperCase(tunnelType);
557 String error = "Invalid tunnel type. Valid values: " +
558 ITMConstants.TUNNEL_TYPE_VXLAN + " | " + ITMConstants.TUNNEL_TYPE_GRE;
559 Preconditions.checkArgument(ITMConstants.TUNNEL_TYPE_VXLAN.equals(tunnelType)
560 || ITMConstants.TUNNEL_TYPE_GRE.equals(tunnelType), error);
564 private static List<BigInteger> getConflictingDpnsAlreadyConfiguredWithTz(String schemaName, String tzone,
565 List<BigInteger> lstDpns, List<VtepConfigSchema> existingSchemas) {
566 List<BigInteger> lstConflictingDpns = new ArrayList<>();
567 for (VtepConfigSchema schema : emptyIfNull(existingSchemas)) {
568 if (!StringUtils.equalsIgnoreCase(schemaName, schema.getSchemaName())
569 && StringUtils.equals(schema.getTransportZoneName(), tzone)) {
570 lstConflictingDpns = new ArrayList<>(getDpnIdList(schema.getDpnIds()));
571 lstConflictingDpns.retainAll(lstDpns);
572 if (!lstConflictingDpns.isEmpty()) {
577 return lstConflictingDpns;
579 public static VtepConfigSchema constructVtepConfigSchema(String schemaName, String portName, Integer vlanId,
580 String subnetMask, String gatewayIp, String transportZone,String tunnelType, List<BigInteger> dpnIds,
581 String excludeIpFilter) {
582 IpAddress gatewayIpObj = StringUtils.isBlank(gatewayIp) ? null : new IpAddress(gatewayIp.toCharArray());
583 IpPrefix subnet = StringUtils.isBlank(subnetMask) ? null : new IpPrefix(subnetMask.toCharArray());
584 Class<? extends TunnelTypeBase> tunType ;
585 if( tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN)) {
586 tunType = TunnelTypeVxlan.class ;
588 tunType = TunnelTypeGre.class ;
590 VtepConfigSchemaBuilder schemaBuilder = new VtepConfigSchemaBuilder().setSchemaName(schemaName)
591 .setPortName(portName).setVlanId(vlanId).setSubnet(subnet).setGatewayIp(gatewayIpObj)
592 .setTransportZoneName(transportZone).setTunnelType(tunType).setDpnIds(getDpnIdsListFromBigInt(dpnIds))
593 .setExcludeIpFilter(excludeIpFilter);
594 return schemaBuilder.build();
596 public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
597 final List<IpAddress> lstIpAddress = new ArrayList<>();
598 if (StringUtils.isBlank(excludeIpFilter)) {
601 final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
602 for (String ip : arrIps) {
603 if (StringUtils.countMatches(ip, "-") == 1) {
604 final String[] arrIpRange = StringUtils.split(ip, '-');
605 String strStartIp = StringUtils.trim(arrIpRange[0]);
606 String strEndIp = StringUtils.trim(arrIpRange[1]);
607 Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
608 "Invalid exclude IP filter: invalid IP address value " + strStartIp);
609 Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
610 "Invalid exclude IP filter: invalid IP address value " + strEndIp);
611 Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
612 "Invalid exclude IP filter: IP address [" + strStartIp +
613 "] not in subnet range " + subnetInfo.getCidrSignature());
614 Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
615 "Invalid exclude IP filter: IP address [" + strEndIp +
616 "] not in subnet range " + subnetInfo.getCidrSignature());
617 int startIp = subnetInfo.asInteger(strStartIp);
618 int endIp = subnetInfo.asInteger(strEndIp);
620 Preconditions.checkArgument(startIp < endIp,
621 "Invalid exclude IP filter: Invalid range [" + ip + "] ");
622 for (int i = startIp; i <= endIp; i++) {
623 String ipAddress = ipFormat(toIpArray(i));
624 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
627 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
632 private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
634 String ip = StringUtils.trim(ipAddress);
635 Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
636 "Invalid exclude IP filter: invalid IP address value " + ip);
637 Preconditions.checkArgument(subnetInfo.isInRange(ip),
638 "Invalid exclude IP filter: IP address [" + ip + "] not in subnet range " +
639 subnetInfo.getCidrSignature());
640 lstIpAddress.add(new IpAddress(ip.toCharArray()));
642 private static int[] toIpArray(int val) {
643 int[] ret = new int[4];
644 for (int j = 3; j >= 0; --j) {
645 ret[j] |= val >>> 8 * (3 - j) & 0xff;
649 private static String ipFormat(int[] octets) {
650 StringBuilder str = new StringBuilder();
651 for (int i = 0; i < octets.length; ++i) {
652 str.append(octets[i]);
653 if (i != octets.length - 1) {
657 return str.toString();
659 public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd,
660 List<BigInteger> lstDpnsForDelete, IITMProvider itmProvider) {
661 Preconditions.checkArgument(StringUtils.isNotBlank(schemaName));
662 if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty())
663 && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) {
664 Preconditions.checkArgument(false,
665 "DPN ID list for add | delete is null or empty in schema " + schemaName);
667 VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName);
668 if (schema == null) {
669 Preconditions.checkArgument(false, "Specified VTEP Schema [" + schemaName +
670 "] doesn't exists!");
672 List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds());
673 if (isNotEmpty(lstDpnsForAdd)) {
674 // if (isNotEmpty(existingDpnIds)) {
675 List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds);
676 lstAlreadyExistingDpns.retainAll(lstDpnsForAdd);
677 Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(),
678 "DPN ID's " + lstAlreadyExistingDpns +
679 " already exists in VTEP schema [" + schemaName + "]");
681 if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
682 validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd, itmProvider.getAllVtepConfigSchemas());
685 if (isNotEmpty(lstDpnsForDelete)) {
686 if (existingDpnIds == null || existingDpnIds.isEmpty()) {
687 String builder = "DPN ID's " + lstDpnsForDelete +
688 " specified for delete from VTEP schema [" + schemaName +
689 "] are not configured in the schema.";
690 Preconditions.checkArgument(false, builder);
691 } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) {
692 List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete);
693 lstConflictingDpns.removeAll(existingDpnIds);
694 String builder = "DPN ID's " + lstConflictingDpns +
695 " specified for delete from VTEP schema [" + schemaName +
696 "] are not configured in the schema.";
697 Preconditions.checkArgument(false, builder);
702 public static String getSubnetCidrAsString(IpPrefix subnet) {
703 return subnet == null ? StringUtils.EMPTY : String.valueOf(subnet.getValue());
705 public static <T> List<T> emptyIfNull(List<T> list) {
706 return list == null ? Collections.emptyList() : list;
708 public static <T> boolean isEmpty(Collection<T> collection) {
709 return collection == null || collection.isEmpty();
711 public static <T> boolean isNotEmpty(Collection<T> collection) {
712 return !isEmpty(collection);
714 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) {
715 HwVtep hwVtep = new HwVtep();
716 hwVtep.setGatewayIP(gatewayIP);
717 hwVtep.setHwIp(ipAddress);
718 hwVtep.setIpPrefix(ipPrefix);
719 hwVtep.setNode_id(node_id);
720 hwVtep.setTopo_id(topo_id);
721 hwVtep.setTransportZone(transportZone.getZoneName());
722 hwVtep.setTunnel_type(tunnel_type);
723 hwVtep.setVlanID(vlanID);
727 public static String getHwParentIf(String topo_id, String srcNodeid) {
728 return String.format("%s:%s", topo_id, srcNodeid);
731 public static <T extends DataObject> void syncWrite(LogicalDatastoreType datastoreType,
732 InstanceIdentifier<T> path, T data, DataBroker broker) {
733 WriteTransaction tx = broker.newWriteOnlyTransaction();
734 tx.put(datastoreType, path, data, true);
735 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
738 } catch (InterruptedException | ExecutionException e) {
739 LOG.error("ITMUtils:SyncWrite , Error writing to datastore (path, data) : ({}, {})", path, data);
740 throw new RuntimeException(e.getMessage());
744 public static List<BigInteger> getDpnIdList( List<DpnIds> dpnIds ) {
745 List<BigInteger> dpnList = new ArrayList<>() ;
746 for( DpnIds dpn : dpnIds) {
747 dpnList.add(dpn.getDPN()) ;
752 public static List<DpnIds> getDpnIdsListFromBigInt( List<BigInteger> dpnIds) {
753 List<DpnIds> dpnIdList = new ArrayList<>() ;
754 DpnIdsBuilder builder = new DpnIdsBuilder() ;
755 for( BigInteger dpnId : dpnIds) {
756 dpnIdList.add(builder.setKey(new DpnIdsKey(dpnId)).setDPN(dpnId).build() );
761 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
762 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> idBuilder =
763 InstanceIdentifier.builder(InterfacesState.class)
764 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.class,
765 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
767 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> id = idBuilder.build();
770 public static Boolean readMonitoringStateFromCache(DataBroker dataBroker) {
771 InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
772 TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
773 if(tunnelMonitorParams!=null) {
774 return tunnelMonitorParams.isEnabled();
776 return ITMConstants.DEFAULT_MONITOR_ENABLED;
780 public static Integer readMonitorIntervalfromCache(DataBroker dataBroker) {
781 InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.create(TunnelMonitorInterval.class);
782 TunnelMonitorInterval tunnelMonitorIOptional = (TunnelMonitorInterval)DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"Interval",dataBroker,true);
783 if(tunnelMonitorIOptional!=null) {
784 return tunnelMonitorIOptional.getInterval();
790 public static Integer determineMonitorInterval(DataBroker dataBroker) {
791 Integer monitorInterval = ItmUtils.readMonitorIntervalfromCache(dataBroker);
792 LOG.debug("determineMonitorInterval: monitorInterval from DS = {}", monitorInterval);
793 if(monitorInterval==null){
794 Class<? extends TunnelMonitoringTypeBase> monitorProtocol = determineMonitorProtocol(dataBroker);
795 if(monitorProtocol.isAssignableFrom(TunnelMonitoringTypeBfd.class)) {
796 monitorInterval = ITMConstants.BFD_DEFAULT_MONITOR_INTERVAL;
798 monitorInterval = ITMConstants.DEFAULT_MONITOR_INTERVAL;
801 LOG.debug("determineMonitorInterval: monitorInterval = {}", monitorInterval);
802 InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.builder(TunnelMonitorInterval.class).build();
803 TunnelMonitorInterval intervalBuilder = new TunnelMonitorIntervalBuilder().setInterval(monitorInterval).build();
804 ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, intervalBuilder, dataBroker, ItmUtils.DEFAULT_CALLBACK);
805 return monitorInterval;
808 public static List<String> getInternalTunnelInterfaces(DataBroker dataBroker){
809 List<String> tunnelList = new ArrayList<>();
810 Collection<String> internalInterfaces = itmCache.getAllInternalInterfaces();
811 if(internalInterfaces == null) {
812 updateTunnelsCache(dataBroker);
813 internalInterfaces = itmCache.getAllInternalInterfaces();
815 LOG.debug("ItmUtils.getTunnelList Cache Internal Interfaces size: {} ", internalInterfaces.size());
816 if(internalInterfaces!=null) {
817 tunnelList.addAll(internalInterfaces);
819 LOG.trace("ItmUtils.getTunnelList Internal: {}", tunnelList);
823 public static List<String> getTunnelsofTzone(List<HwVtep> hwVteps, String tzone, DataBroker dataBroker, Boolean hwVtepsExist) {
825 List<String> tunnels = new ArrayList<>();
826 InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
827 child(TransportZone.class, new TransportZoneKey(tzone)).build();
828 Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
829 if (tZoneOptional.isPresent()) {
830 TransportZone transportZone = tZoneOptional.get();
831 Class<? extends TunnelTypeBase> tunType = transportZone.getTunnelType();
832 if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
833 for (Subnets sub : transportZone.getSubnets()) {
834 if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
835 for (Vteps vtepLocal : sub.getVteps()) {
836 for (Vteps vtepRemote : sub.getVteps()) {
837 if (!vtepLocal.equals(vtepRemote)) {
838 InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(), tunType);
839 InstanceIdentifier<InternalTunnel> intIID =
840 InstanceIdentifier.builder(TunnelList.class).
841 child(InternalTunnel.class, key).build();
842 Optional<InternalTunnel> TunnelsOptional =
843 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
844 if (TunnelsOptional.isPresent()) {
845 String tunnelInterfaceName = TunnelsOptional.get().getTunnelInterfaceName();
846 LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
847 tunnels.add(tunnelInterfaceName);
851 if(hwVteps!= null && !hwVteps.isEmpty()) {
852 for (HwVtep hwVtep : hwVteps) {
853 tunnels.add(getExtTunnel(hwVtep.getNode_id(), vtepLocal.getDpnId().toString(),
854 tunType, dataBroker));
855 tunnels.add(getExtTunnel(vtepLocal.getDpnId().toString(), hwVtep.getNode_id(),
856 tunType, dataBroker));
864 for (HwVtep hwVtep : hwVteps) {
865 for (HwVtep hwVtepOther : hwVteps) {
866 if (!hwVtep.getHwIp().equals(hwVtepOther.getHwIp())) {
867 tunnels.add(getExtTunnel(hwVtep.getNode_id(), hwVtepOther.getNode_id(), tunType, dataBroker));
868 tunnels.add(getExtTunnel(hwVtepOther.getNode_id(), hwVtep.getNode_id(), tunType, dataBroker));
877 public static List<String> getInternalTunnelsofTzone(String tzone, DataBroker dataBroker) {
878 List<String> tunnels = new ArrayList<>();
879 LOG.trace("Getting internal tunnels of {}",tzone);
880 InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class).
881 child(TransportZone.class, new TransportZoneKey(tzone)).build();
882 Optional<TransportZone> tZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
883 if (tZoneOptional.isPresent()) {
884 TransportZone transportZone = tZoneOptional.get();
885 if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
886 for (Subnets sub : transportZone.getSubnets()) {
887 if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
888 for (Vteps vtepLocal : sub.getVteps()) {
889 for (Vteps vtepRemote : sub.getVteps()) {
890 if (!vtepLocal.equals(vtepRemote)) {
891 InternalTunnelKey key =
892 new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(),
893 transportZone.getTunnelType());
894 InstanceIdentifier<InternalTunnel> intIID =
895 InstanceIdentifier.builder(TunnelList.class).
896 child(InternalTunnel.class, key).build();
897 Optional<InternalTunnel> tunnelsOptional =
898 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
899 if (tunnelsOptional.isPresent()) {
900 String tunnelInterfaceName = tunnelsOptional.get().getTunnelInterfaceName();
901 LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
902 tunnels.add(tunnelInterfaceName);
914 private static String getExtTunnel(String node_id, String dpId,Class<? extends TunnelTypeBase> tunType, DataBroker dataBroker) {
915 LOG.trace("getting ext tunnel for {} and dpId {}",node_id,dpId);
916 ExternalTunnelKey key = getExternalTunnelKey(dpId, node_id, tunType);
917 InstanceIdentifier<ExternalTunnel> intIID = InstanceIdentifier.builder(ExternalTunnelList.class).
918 child(ExternalTunnel.class, key).build();
919 Optional<ExternalTunnel> tunnelsOptional =
920 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
921 if (tunnelsOptional.isPresent()) {
922 String tunnelInterfaceName = tunnelsOptional.get().getTunnelInterfaceName();
923 LOG.trace("ext tunnel returned {} ", tunnelInterfaceName);
924 return tunnelInterfaceName;
928 public static ExternalTunnelKey getExternalTunnelKey(String dst , String src, Class<? extends TunnelTypeBase> tunType) {
929 if (src.indexOf("physicalswitch") > 0) {
930 src = src.substring(0, src.indexOf("physicalswitch") - 1);
932 if (dst.indexOf("physicalswitch") > 0) {
933 dst = dst.substring(0, dst.indexOf("physicalswitch") - 1);
935 return new ExternalTunnelKey(dst, src, tunType);
938 public static List<TunnelEndPoints> getTEPsForDpn( BigInteger srcDpn, List<DPNTEPsInfo> dpnList) {
939 for (DPNTEPsInfo dpn : dpnList) {
940 if( dpn.getDPNID().equals(srcDpn)) {
941 return dpn.getTunnelEndPoints() ;
946 public static TunnelList getAllInternalTunnels(DataBroker broker) {
947 InstanceIdentifier<TunnelList> tunnelListInstanceIdentifier = InstanceIdentifier.builder(TunnelList.class).build();
948 return read(LogicalDatastoreType.CONFIGURATION, tunnelListInstanceIdentifier, broker).orNull();
950 public static InternalTunnel getInternalTunnel(String interfaceName, DataBroker broker) {
951 InternalTunnel internalTunnel = null;
952 TunnelList tunnelList = getAllInternalTunnels(broker);
953 if (tunnelList != null && tunnelList.getInternalTunnel() != null) {
954 List<InternalTunnel> internalTunnels = tunnelList.getInternalTunnel();
955 for (InternalTunnel tunnel : internalTunnels) {
956 if (tunnel.getTunnelInterfaceName().equalsIgnoreCase(interfaceName)) {
957 internalTunnel = tunnel;
962 return internalTunnel;
964 public static ExternalTunnel getExternalTunnel(String interfaceName, DataBroker broker) {
965 ExternalTunnel externalTunnel = null;
966 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker);
967 for (ExternalTunnel tunnel : externalTunnels) {
968 if (StringUtils.equalsIgnoreCase(interfaceName, tunnel.getTunnelInterfaceName())) {
969 externalTunnel = tunnel;
973 return externalTunnel;
975 public static List<ExternalTunnel> getAllExternalTunnels(DataBroker broker) {
976 List<ExternalTunnel> result = null;
977 InstanceIdentifier<ExternalTunnelList> id = InstanceIdentifier.builder(ExternalTunnelList.class).build();
978 Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, id, broker);
979 if (tunnelList.isPresent()) {
980 result = tunnelList.get().getExternalTunnel();
982 if (result == null) {
983 result = Collections.emptyList();
987 public static String convertTunnelTypetoString(Class<? extends TunnelTypeBase> tunType ) {
988 String tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
989 if( tunType.equals(TunnelTypeVxlan.class)) {
990 tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN ;
991 } else if( tunType.equals(TunnelTypeGre.class) ) {
992 tunnelType = ITMConstants.TUNNEL_TYPE_GRE ;
993 } else if (tunnelType.equals(TunnelTypeMplsOverGre.class)) {
994 tunnelType = ITMConstants.TUNNEL_TYPE_MPLSoGRE;
1000 public static boolean isItmIfType(Class<? extends InterfaceType> ifType) {
1001 return ifType != null && ifType.isAssignableFrom(Tunnel.class);
1004 public static StateTunnelListKey getTunnelStateKey( org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface iface) {
1005 StateTunnelListKey key = null;
1006 if(isItmIfType(iface.getType())) {
1007 key = new StateTunnelListKey(iface.getName());
1012 public static void updateTunnelsCache(DataBroker broker) {
1013 List<InternalTunnel> internalTunnels = getAllInternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
1014 for (InternalTunnel tunnel : internalTunnels) {
1015 itmCache.addInternalTunnel(tunnel);
1017 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
1018 for (ExternalTunnel tunnel : externalTunnels) {
1019 itmCache.addExternalTunnel(tunnel);
1023 public static List<ExternalTunnel> getAllExternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
1024 List<ExternalTunnel> result = null;
1025 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1026 Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1027 if (tunnelList.isPresent()) {
1028 result = tunnelList.get().getExternalTunnel();
1030 if (result == null) {
1031 result = Collections.emptyList();
1036 public static List<InternalTunnel> getAllInternalTunnels(DataBroker dataBroker, LogicalDatastoreType datastoreType) {
1037 List<InternalTunnel> result = null;
1038 InstanceIdentifier<TunnelList> iid = InstanceIdentifier.builder(TunnelList.class).build();
1039 Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1040 if (tunnelList.isPresent()) {
1041 result = tunnelList.get().getInternalTunnel();
1043 if (result == null) {
1044 result = Collections.emptyList();
1049 public static Interface getInterface(
1050 String name, DataBroker broker) {
1051 Interface result = itmCache.getInterface(name);
1052 if (result == null) {
1053 InstanceIdentifier<Interface> iid =
1054 InstanceIdentifier.builder(Interfaces.class)
1055 .child(Interface.class, new InterfaceKey(name)).build();
1056 Optional<Interface> optInterface = read(LogicalDatastoreType.CONFIGURATION, iid, broker);
1057 if (optInterface.isPresent()) {
1058 result = optInterface.get();
1059 itmCache.addInterface(result);
1065 public static Class<? extends TunnelMonitoringTypeBase> readMonitoringProtocolFromCache(DataBroker dataBroker) {
1066 InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
1067 TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache.get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
1068 if(tunnelMonitorParams!=null) {
1069 return tunnelMonitorParams.getMonitorProtocol();
1074 public static Class<? extends TunnelMonitoringTypeBase> determineMonitorProtocol(DataBroker dataBroker) {
1075 Class<? extends TunnelMonitoringTypeBase> monitoringProtocol = ItmUtils.readMonitoringProtocolFromCache(dataBroker);
1076 LOG.debug("determineMonitorProtocol: monitorProtocol from DS = {}", monitoringProtocol);
1077 if(monitoringProtocol==null) {
1078 monitoringProtocol = ITMConstants.DEFAULT_MONITOR_PROTOCOL;
1080 LOG.debug("determineMonitorProtocol: monitorProtocol = {}", monitoringProtocol);
1081 Boolean monitorState = ItmUtils.readMonitoringStateFromCache(dataBroker);
1082 if(monitorState==null) {
1083 monitorState = true;
1085 LOG.debug("determineMonitorProtocol: monitorState = {}", monitorState);
1086 InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.builder(TunnelMonitorParams.class).build();
1087 TunnelMonitorParams protocolBuilder = new TunnelMonitorParamsBuilder().setEnabled(monitorState).setMonitorProtocol(monitoringProtocol).build();
1088 ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, protocolBuilder, dataBroker, ItmUtils.DEFAULT_CALLBACK);
1089 return monitoringProtocol;
1092 public static List<DcGatewayIp> getDcGatewayIpList(DataBroker broker){
1093 InstanceIdentifier<DcGatewayIpList> dcGatewayIpListid = InstanceIdentifier.builder(DcGatewayIpList.class).build();
1094 Optional<DcGatewayIpList> dcGatewayIpListConfig = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, dcGatewayIpListid, broker);
1095 if(dcGatewayIpListConfig.isPresent()){
1096 DcGatewayIpList containerList = dcGatewayIpListConfig.get();
1097 if(containerList != null){
1098 return containerList.getDcGatewayIp();
1104 public static boolean falseIfNull(Boolean value) {
1105 return value == null ? false : value;
1108 public static <T> List<T> getIntersection(List<T> list1, List<T> list2) {
1109 List<T> list = new ArrayList<>();
1111 if(list2.contains(t)) {
1118 public static void addTransportZoneMembership(List<TzMembership> zones, String zoneName) {
1119 zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());
1122 public static List<TzMembership> createTransportZoneMembership(String zoneName) {
1123 List<TzMembership> zones = new ArrayList<>();
1124 zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());