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.collect.ImmutableMap;
13 import com.google.common.net.InetAddresses;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import java.math.BigInteger;
18 import java.net.InetAddress;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.List;
23 import java.util.UUID;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.Future;
27 import org.apache.commons.lang3.StringUtils;
28 import org.apache.commons.net.util.SubnetUtils;
29 import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
30 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
31 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
32 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
33 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
34 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
35 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
36 import org.opendaylight.genius.interfacemanager.globals.IfmConstants;
37 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
38 import org.opendaylight.genius.itm.api.IITMProvider;
39 import org.opendaylight.genius.itm.confighelpers.HwVtep;
40 import org.opendaylight.genius.itm.confighelpers.ItmTunnelAggregationHelper;
41 import org.opendaylight.genius.itm.globals.ITMConstants;
42 import org.opendaylight.genius.mdsalutil.ActionInfo;
43 import org.opendaylight.genius.mdsalutil.FlowEntity;
44 import org.opendaylight.genius.mdsalutil.InstructionInfo;
45 import org.opendaylight.genius.mdsalutil.MDSALUtil;
46 import org.opendaylight.genius.mdsalutil.MatchInfo;
47 import org.opendaylight.genius.mdsalutil.NwConstants;
48 import org.opendaylight.genius.mdsalutil.actions.ActionPuntToController;
49 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
50 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
51 import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
52 import org.opendaylight.genius.utils.cache.DataStoreCache;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.Tunnel;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
59 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
60 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
61 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlan;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlanBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnelBuilder;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefsBuilder;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelMonitoringTypeBase;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelMonitoringTypeBfd;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeGre;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeLogicalGroup;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeMplsOverGre;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifier;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.interfaces._interface.NodeIdentifierKey;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorInterval;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorIntervalBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorParams;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.TunnelMonitorParamsBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.VtepConfigSchemas;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.VtepIpPools;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchema;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.VtepConfigSchemaKey;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIds;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsBuilder;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.config.schemas.vtep.config.schema.DpnIdsKey;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPool;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.config.rev160406.vtep.ip.pools.VtepIpPoolKey;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpoints;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.DpnEndpointsBuilder;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeBase;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeExternal;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeHwvtep;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TepTypeInternal;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelList;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelOperStatus;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelsState;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfo;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoBuilder;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfoKey;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPoints;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsBuilder;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPointsKey;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.tunnel.end.points.TzMembership;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.tunnel.end.points.TzMembershipBuilder;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelBuilder;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnel;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelKey;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.StateTunnelList;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.StateTunnelListBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.StateTunnelListKey;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.state.tunnel.list.DstInfoBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnels_state.state.tunnel.list.SrcInfoBuilder;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.DcGatewayIpList;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.TransportZones;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.dc.gateway.ip.list.DcGatewayIp;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TepsNotHostedInTransportZone;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TepsNotHostedInTransportZoneKey;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZone;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZoneKey;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.Subnets;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.subnets.Vteps;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
138 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
139 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
140 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
141 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
142 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
143 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
144 import org.opendaylight.yangtools.yang.binding.DataObject;
145 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
146 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
147 import org.opendaylight.yangtools.yang.common.RpcResult;
148 import org.slf4j.Logger;
149 import org.slf4j.LoggerFactory;
151 public class ItmUtils {
153 public static final String DUMMY_IP_ADDRESS = "0.0.0.0";
154 public static final String TUNNEL_TYPE_VXLAN = "VXLAN";
155 public static final String TUNNEL_TYPE_GRE = "GRE";
156 public static final String TUNNEL = "tun";
157 public static final IpPrefix DUMMY_IP_PREFIX = new IpPrefix(ITMConstants.DUMMY_PREFIX.toCharArray());
158 public static ItmCache itmCache = new ItmCache();
160 private static final Logger LOG = LoggerFactory.getLogger(ItmUtils.class);
162 public static final ImmutableMap<String, Class<? extends TunnelTypeBase>>
164 new ImmutableMap.Builder<String, Class<? extends TunnelTypeBase>>()
165 .put(ITMConstants.TUNNEL_TYPE_GRE, TunnelTypeGre.class)
166 .put(ITMConstants.TUNNEL_TYPE_MPLSoGRE, TunnelTypeMplsOverGre.class)
167 .put(ITMConstants.TUNNEL_TYPE_VXLAN, TunnelTypeVxlan.class)
170 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
172 public void onSuccess(Void result) {
173 LOG.debug("Success in Datastore write operation");
177 public void onFailure(Throwable error) {
178 LOG.error("Error in Datastore write operation", error);
182 @SuppressWarnings("checkstyle:IllegalCatch")
183 public static <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
184 InstanceIdentifier<T> path, DataBroker broker) {
185 try (ReadOnlyTransaction tx = broker.newReadOnlyTransaction()) {
186 return tx.read(datastoreType, path).get();
187 } catch (Exception e) {
188 throw new RuntimeException(e);
192 public static <T extends DataObject> void asyncWrite(LogicalDatastoreType datastoreType,
193 InstanceIdentifier<T> path, T data, DataBroker broker,
194 FutureCallback<Void> callback) {
195 WriteTransaction tx = broker.newWriteOnlyTransaction();
196 tx.put(datastoreType, path, data, true);
197 Futures.addCallback(tx.submit(), callback);
200 public static <T extends DataObject> void asyncUpdate(LogicalDatastoreType datastoreType,
201 InstanceIdentifier<T> path, T data, DataBroker broker,
202 FutureCallback<Void> callback) {
203 WriteTransaction tx = broker.newWriteOnlyTransaction();
204 tx.merge(datastoreType, path, data, true);
205 Futures.addCallback(tx.submit(), callback);
208 public static <T extends DataObject> void asyncDelete(LogicalDatastoreType datastoreType,
209 InstanceIdentifier<T> path, DataBroker broker,
210 FutureCallback<Void> callback) {
211 WriteTransaction tx = broker.newWriteOnlyTransaction();
212 tx.delete(datastoreType, path);
213 Futures.addCallback(tx.submit(), callback);
216 public static <T extends DataObject> void asyncBulkRemove(final DataBroker broker,
217 final LogicalDatastoreType datastoreType,
218 List<InstanceIdentifier<T>> pathList,
219 FutureCallback<Void> callback) {
220 if (!pathList.isEmpty()) {
221 WriteTransaction tx = broker.newWriteOnlyTransaction();
222 for (InstanceIdentifier<T> path : pathList) {
223 tx.delete(datastoreType, path);
225 Futures.addCallback(tx.submit(), callback);
229 public static String getInterfaceName(final BigInteger datapathid, final String portName, final Integer vlanId) {
230 return String.format("%s:%s:%s", datapathid, portName, vlanId);
233 public static BigInteger getDpnIdFromInterfaceName(String interfaceName) {
234 String[] dpnStr = interfaceName.split(":");
235 BigInteger dpnId = new BigInteger(dpnStr[0]);
239 public static String getTrunkInterfaceName(IdManagerService idManager, String parentInterfaceName,
240 String localHostName, String remoteHostName, String tunnelType) {
241 String tunnelTypeStr;
242 if (tunnelType.contains("TunnelTypeGre")) {
243 tunnelTypeStr = ITMConstants.TUNNEL_TYPE_GRE;
244 } else if (tunnelType.contains("TunnelTypeLogicalGroup")) {
245 tunnelTypeStr = ITMConstants.TUNNEL_TYPE_LOGICAL_GROUP_VXLAN;
247 tunnelTypeStr = ITMConstants.TUNNEL_TYPE_VXLAN;
249 String trunkInterfaceName = String.format("%s:%s:%s:%s", parentInterfaceName, localHostName,
250 remoteHostName, tunnelTypeStr);
251 LOG.trace("trunk interface name is {}", trunkInterfaceName);
252 trunkInterfaceName = String.format("%s%s", TUNNEL, getUniqueIdString(trunkInterfaceName));
253 return trunkInterfaceName;
256 public static void releaseIdForTrunkInterfaceName(IdManagerService idManager, String parentInterfaceName,
257 String localHostName, String remoteHostName, String tunnelType) {
258 String tunnelTypeStr;
259 if (tunnelType.contains("TunnelTypeGre")) {
260 tunnelTypeStr = ITMConstants.TUNNEL_TYPE_GRE;
262 tunnelTypeStr = ITMConstants.TUNNEL_TYPE_VXLAN;
264 String trunkInterfaceName = String.format("%s:%s:%s:%s", parentInterfaceName, localHostName,
265 remoteHostName, tunnelTypeStr);
266 LOG.trace("Releasing Id for trunkInterface - {}", trunkInterfaceName);
267 //releaseId(idManager, trunkInterfaceName) ;
270 public static String getLogicalTunnelGroupName(BigInteger srcDpnId, BigInteger destDpnId) {
271 String tunnelTypeStr = ITMConstants.TUNNEL_TYPE_LOGICAL_GROUP_VXLAN;
272 String groupName = String.format("%s:%s:%s", srcDpnId.toString(), destDpnId.toString(), tunnelTypeStr);
273 LOG.trace("logical tunnel group name is {}", groupName);
274 groupName = String.format("%s%s", TUNNEL, getUniqueIdString(groupName));
278 public static InetAddress getInetAddressFromIpAddress(IpAddress ip) {
279 return InetAddresses.forString(ip.getIpv4Address().getValue());
282 public static InstanceIdentifier<DPNTEPsInfo> getDpnTepInstance(BigInteger dpIdKey) {
283 InstanceIdentifier.InstanceIdentifierBuilder<DPNTEPsInfo> dpnTepInfoBuilder =
284 InstanceIdentifier.builder(DpnEndpoints.class).child(DPNTEPsInfo.class,
285 new DPNTEPsInfoKey(dpIdKey));
286 InstanceIdentifier<DPNTEPsInfo> dpnInfo = dpnTepInfoBuilder.build();
290 public static DPNTEPsInfo createDPNTepInfo(BigInteger dpId, List<TunnelEndPoints> endpoints) {
291 return new DPNTEPsInfoBuilder().setKey(new DPNTEPsInfoKey(dpId)).setTunnelEndPoints(endpoints).build();
294 public static TunnelEndPoints createTunnelEndPoints(BigInteger dpnId, IpAddress ipAddress, String portName,
295 boolean isOfTunnel, int vlanId, IpPrefix prefix,
296 IpAddress gwAddress, List<TzMembership> zones,
297 Class<? extends TunnelTypeBase> tunnelType) {
298 // when Interface Mgr provides support to take in Dpn Id
299 return new TunnelEndPointsBuilder().setKey(new TunnelEndPointsKey(ipAddress, portName,tunnelType, vlanId))
300 .setSubnetMask(prefix).setGwIpAddress(gwAddress).setTzMembership(zones)
301 .setOptionOfTunnel(isOfTunnel).setInterfaceName(ItmUtils.getInterfaceName(dpnId, portName, vlanId))
302 .setTunnelType(tunnelType).build();
305 public static DpnEndpoints createDpnEndpoints(List<DPNTEPsInfo> dpnTepInfo) {
306 return new DpnEndpointsBuilder().setDPNTEPsInfo(dpnTepInfo).build();
309 public static InstanceIdentifier<Interface> buildId(String interfaceName) {
310 InstanceIdentifierBuilder<Interface> idBuilder =
311 InstanceIdentifier.builder(Interfaces.class).child(Interface.class, new InterfaceKey(interfaceName));
312 InstanceIdentifier<Interface> id = idBuilder.build();
316 public static Interface buildLogicalTunnelInterface(BigInteger dpn, String ifName, String desc, boolean enabled) {
317 InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(ifName)).setName(ifName)
318 .setDescription(desc).setEnabled(enabled).setType(Tunnel.class);
319 ParentRefs parentRefs = new ParentRefsBuilder().setDatapathNodeIdentifier(dpn).build();
320 builder.addAugmentation(ParentRefs.class, parentRefs);
322 IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(new IpAddress("0.0.0.0".toCharArray()))
323 .setTunnelSource(new IpAddress("0.0.0.0".toCharArray())).setInternal(true).setMonitorEnabled(false)
324 .setTunnelInterfaceType(TunnelTypeLogicalGroup.class).setTunnelRemoteIpFlow(false).build();
325 builder.addAugmentation(IfTunnel.class, tunnel);
326 return builder.build();
329 public static Interface buildTunnelInterface(BigInteger dpn, String ifName, String desc, boolean enabled,
330 Class<? extends TunnelTypeBase> tunType, IpAddress localIp,
331 IpAddress remoteIp, IpAddress gatewayIp, Integer vlanId,
332 boolean internal, Boolean monitorEnabled,
333 Class<? extends TunnelMonitoringTypeBase> monitorProtocol,
334 Integer monitorInterval, boolean useOfTunnel) {
336 return buildTunnelInterface(dpn, ifName, desc, enabled, tunType, localIp, remoteIp, gatewayIp, vlanId,
337 internal, monitorEnabled, monitorProtocol, monitorInterval, useOfTunnel, null);
340 public static Interface buildTunnelInterface(BigInteger dpn, String ifName, String desc, boolean enabled,
341 Class<? extends TunnelTypeBase> tunType, IpAddress localIp,
342 IpAddress remoteIp, IpAddress gatewayIp, Integer vlanId,
343 boolean internal, Boolean monitorEnabled,
344 Class<? extends TunnelMonitoringTypeBase> monitorProtocol,
345 Integer monitorInterval, boolean useOfTunnel, String parentIfaceName) {
346 InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(ifName)).setName(ifName)
347 .setDescription(desc).setEnabled(enabled).setType(Tunnel.class);
348 ParentRefs parentRefs =
349 new ParentRefsBuilder().setDatapathNodeIdentifier(dpn).setParentInterface(parentIfaceName).build();
350 builder.addAugmentation(ParentRefs.class, parentRefs);
351 Long monitoringInterval = null;
353 IfL2vlan l2vlan = new IfL2vlanBuilder().setVlanId(new VlanId(vlanId)).build();
354 builder.addAugmentation(IfL2vlan.class, l2vlan);
356 LOG.debug("buildTunnelInterface: monitorProtocol = {} and monitorInterval = {}",
357 monitorProtocol.getName(),monitorInterval);
359 if (monitorInterval != null) {
360 monitoringInterval = monitorInterval.longValue();
363 IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(remoteIp).setTunnelGateway(gatewayIp)
364 .setTunnelSource(localIp).setTunnelInterfaceType(tunType).setInternal(internal)
365 .setMonitorEnabled(monitorEnabled).setMonitorProtocol(monitorProtocol)
366 .setMonitorInterval(monitoringInterval).setTunnelRemoteIpFlow(useOfTunnel)
368 builder.addAugmentation(IfTunnel.class, tunnel);
369 return builder.build();
372 public static Interface buildHwTunnelInterface(String tunnelIfName, String desc, boolean enabled, String topoId,
373 String nodeId, Class<? extends TunnelTypeBase> tunType,
374 IpAddress srcIp, IpAddress destIp, IpAddress gwIp,
375 Boolean monitorEnabled,
376 Class<? extends TunnelMonitoringTypeBase> monitorProtocol,
377 Integer monitorInterval) {
378 InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(tunnelIfName))
379 .setName(tunnelIfName).setDescription(desc).setEnabled(enabled).setType(Tunnel.class);
380 List<NodeIdentifier> nodeIds = new ArrayList<>();
381 NodeIdentifier hwNode = new NodeIdentifierBuilder().setKey(new NodeIdentifierKey(topoId))
382 .setTopologyId(topoId).setNodeId(nodeId).build();
384 ParentRefs parent = new ParentRefsBuilder().setNodeIdentifier(nodeIds).build();
385 builder.addAugmentation(ParentRefs.class, parent);
386 Long monitoringInterval = (long) ITMConstants.DEFAULT_MONITOR_INTERVAL;
387 Boolean monitoringEnabled = true;
388 Class<? extends TunnelMonitoringTypeBase> monitoringProtocol = ITMConstants.DEFAULT_MONITOR_PROTOCOL;
389 if (monitoringInterval != null) {
390 monitoringInterval = monitorInterval.longValue();
392 if (monitorEnabled != null) {
393 monitoringEnabled = monitorEnabled;
395 if (monitorProtocol != null) {
396 monitoringProtocol = monitorProtocol;
398 IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(destIp).setTunnelGateway(gwIp)
399 .setTunnelSource(srcIp).setMonitorEnabled(monitoringEnabled).setMonitorProtocol(monitorProtocol)
400 .setMonitorInterval(100L).setTunnelInterfaceType(tunType).setInternal(false).build();
401 builder.addAugmentation(IfTunnel.class, tunnel);
402 LOG.trace("iftunnel {} built from hwvtep {} ", tunnel, nodeId);
403 return builder.build();
407 public static InternalTunnel buildInternalTunnel(BigInteger srcDpnId, BigInteger dstDpnId,
408 Class<? extends TunnelTypeBase> tunType,
409 String trunkInterfaceName) {
410 InternalTunnel tnl = new InternalTunnelBuilder().setKey(new InternalTunnelKey(dstDpnId, srcDpnId, tunType))
411 .setDestinationDPN(dstDpnId)
412 .setSourceDPN(srcDpnId).setTransportType(tunType)
413 .setTunnelInterfaceNames(Collections.singletonList(trunkInterfaceName)).build();
417 public static ExternalTunnel buildExternalTunnel(String srcNode, String dstNode,
418 Class<? extends TunnelTypeBase> tunType,
419 String trunkInterfaceName) {
420 ExternalTunnel extTnl = new ExternalTunnelBuilder().setKey(
421 new ExternalTunnelKey(dstNode, srcNode, tunType))
422 .setSourceDevice(srcNode).setDestinationDevice(dstNode)
423 .setTunnelInterfaceName(trunkInterfaceName)
424 .setTransportType(tunType).build();
428 public static List<DPNTEPsInfo> getTunnelMeshInfo(DataBroker dataBroker) {
429 List<DPNTEPsInfo> dpnTEPs = null ;
431 // Read the Mesh Information from Cache if not read from the DS
432 dpnTEPs = getTunnelMeshInfo() ;
433 if (dpnTEPs != null) {
437 // Read the EndPoint Info from the operational database
438 InstanceIdentifierBuilder<DpnEndpoints> depBuilder = InstanceIdentifier.builder(DpnEndpoints.class);
439 InstanceIdentifier<DpnEndpoints> deps = depBuilder.build();
440 Optional<DpnEndpoints> dpnEps = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, deps, dataBroker);
441 if (dpnEps.isPresent()) {
442 DpnEndpoints tn = dpnEps.get();
443 dpnTEPs = tn.getDPNTEPsInfo();
444 LOG.debug("Read from CONFIGURATION datastore - No. of Dpns " , dpnTEPs.size());
446 LOG.debug("No Dpn information in CONFIGURATION datastore ");
451 // Reading the Mesh Information from Cache
452 public static List<DPNTEPsInfo> getTunnelMeshInfo() {
453 List<DPNTEPsInfo> dpnTepsInfo = null ;
454 List<Object> values = null ;
456 values = DataStoreCache.getValues(ITMConstants.DPN_TEPs_Info_CACHE_NAME);
457 if (values != null) {
458 dpnTepsInfo = new ArrayList<>() ;
459 for (Object value : values) {
460 dpnTepsInfo.add((DPNTEPsInfo)value) ;
466 public static int getUniqueId(IdManagerService idManager, String idKey) {
467 AllocateIdInput getIdInput = new AllocateIdInputBuilder()
468 .setPoolName(ITMConstants.ITM_IDPOOL_NAME)
469 .setIdKey(idKey).build();
472 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
473 RpcResult<AllocateIdOutput> rpcResult = result.get();
474 if (rpcResult.isSuccessful()) {
475 return rpcResult.getResult().getIdValue().intValue();
477 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
479 } catch (InterruptedException | ExecutionException e) {
480 LOG.warn("Exception when getting Unique Id",e);
485 public static String getUniqueIdString(String idKey) {
486 return UUID.nameUUIDFromBytes(idKey.getBytes()).toString().substring(0, 12).replace("-", "");
489 public static void releaseId(IdManagerService idManager, String idKey) {
490 ReleaseIdInput idInput =
491 new ReleaseIdInputBuilder().setPoolName(ITMConstants.ITM_IDPOOL_NAME).setIdKey(idKey).build();
493 Future<RpcResult<Void>> result = idManager.releaseId(idInput);
494 RpcResult<Void> rpcResult = result.get();
495 if (!rpcResult.isSuccessful()) {
496 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
498 } catch (InterruptedException | ExecutionException e) {
499 LOG.warn("Exception when getting Unique Id for key {}", idKey, e);
503 public static List<DPNTEPsInfo> getDpnTepListFromDpnId(DataBroker dataBroker, List<BigInteger> dpnIds) {
504 List<DPNTEPsInfo> meshedDpnList = getTunnelMeshInfo(dataBroker) ;
505 List<DPNTEPsInfo> cfgDpnList = new ArrayList<>();
506 if (null != meshedDpnList) {
507 for (BigInteger dpnId : dpnIds) {
508 for (DPNTEPsInfo teps : meshedDpnList) {
509 if (dpnId.equals(teps.getDPNID())) {
510 cfgDpnList.add(teps);
518 @SuppressWarnings("checkstyle:IllegalCatch")
519 public static void setUpOrRemoveTerminatingServiceTable(BigInteger dpnId, IMdsalApiManager mdsalManager,
521 String logmsg = addFlag ? "Installing" : "Removing";
522 LOG.trace(logmsg + " PUNT to Controller flow in DPN {} ", dpnId);
523 List<ActionInfo> listActionInfo = new ArrayList<>();
524 listActionInfo.add(new ActionPuntToController());
527 List<MatchInfo> mkMatches = new ArrayList<>();
529 mkMatches.add(new MatchTunnelId(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)));
531 List<InstructionInfo> mkInstructions = new ArrayList<>();
532 mkInstructions.add(new InstructionApplyActions(listActionInfo));
534 FlowEntity terminatingServiceTableFlowEntity = MDSALUtil
535 .buildFlowEntity(dpnId, NwConstants.INTERNAL_TUNNEL_TABLE,
536 getFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE, ITMConstants.LLDP_SERVICE_ID),
537 5, String.format("%s:%d","ITM Flow Entry ", ITMConstants.LLDP_SERVICE_ID), 0, 0,
538 ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)),
539 mkMatches, mkInstructions);
541 mdsalManager.installFlow(terminatingServiceTableFlowEntity);
543 mdsalManager.removeFlow(terminatingServiceTableFlowEntity);
545 } catch (Exception e) {
546 LOG.error("Error while setting up Table 36 for {}", dpnId, e);
550 private static String getFlowRef(long termSvcTable, int svcId) {
551 return String.valueOf(termSvcTable) + svcId;
554 public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier(String schemaName) {
555 return InstanceIdentifier.builder(VtepConfigSchemas.class)
556 .child(VtepConfigSchema.class, new VtepConfigSchemaKey(schemaName)).build();
559 public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier() {
560 return InstanceIdentifier.builder(VtepConfigSchemas.class).child(VtepConfigSchema.class).build();
563 public static InstanceIdentifier<VtepConfigSchemas> getVtepConfigSchemasIdentifier() {
564 return InstanceIdentifier.builder(VtepConfigSchemas.class).build();
567 public static InstanceIdentifier<VtepIpPool> getVtepIpPoolIdentifier(String subnetCidr) {
568 return InstanceIdentifier.builder(VtepIpPools.class).child(VtepIpPool.class, new VtepIpPoolKey(subnetCidr))
572 public static VtepConfigSchema validateForAddVtepConfigSchema(VtepConfigSchema schema,
573 List<VtepConfigSchema> existingSchemas) {
574 VtepConfigSchema validSchema = validateVtepConfigSchema(schema);
575 for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
576 if (!StringUtils.equalsIgnoreCase(schema.getSchemaName(), existingSchema.getSchemaName())
577 && schema.getSubnet().equals(existingSchema.getSubnet())) {
578 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
579 Preconditions.checkArgument(false, "VTEP schema with subnet [" + subnetCidr
580 + "] already exists. Multiple VTEP schemas with same subnet is not allowed.");
583 if (isNotEmpty(getDpnIdList(validSchema.getDpnIds()))) {
584 String tzone = validSchema.getTransportZoneName();
585 List<BigInteger> lstDpns = getConflictingDpnsAlreadyConfiguredWithTz(validSchema.getSchemaName(), tzone,
586 getDpnIdList(validSchema.getDpnIds()), existingSchemas);
587 if (!lstDpns.isEmpty()) {
588 Preconditions.checkArgument(false, "DPN's " + lstDpns + " already configured for transport zone "
589 + tzone + ". Only one end point per transport Zone per Dpn is allowed.");
591 if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
592 validateForSingleGreTep(validSchema.getSchemaName(), getDpnIdList(validSchema.getDpnIds()),
599 private static void validateForSingleGreTep(String schemaName, List<BigInteger> lstDpnsForAdd,
600 List<VtepConfigSchema> existingSchemas) {
601 for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
602 if (TunnelTypeGre.class.equals(existingSchema.getTunnelType())
603 && !StringUtils.equalsIgnoreCase(schemaName, existingSchema.getSchemaName())) {
604 List<BigInteger> lstConflictingDpns = new ArrayList<>(getDpnIdList(existingSchema.getDpnIds()));
605 lstConflictingDpns.retainAll(emptyIfNull(lstDpnsForAdd));
606 if (!lstConflictingDpns.isEmpty()) {
607 String errMsg = "DPN's " + lstConflictingDpns
608 + " already configured with GRE TEP. Mutiple GRE TEP's on a single DPN are not allowed.";
609 Preconditions.checkArgument(false, errMsg);
615 public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
616 Preconditions.checkNotNull(schema);
617 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
618 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
619 Preconditions.checkArgument(schema.getVlanId() >= 0 && schema.getVlanId() < 4095,
620 "Invalid VLAN ID, range (0-4094)");
621 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
622 Preconditions.checkNotNull(schema.getSubnet());
623 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
624 SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
625 IpAddress gatewayIp = schema.getGatewayIp();
626 if (gatewayIp != null) {
627 String strGatewayIp = String.valueOf(gatewayIp.getValue());
628 if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS) && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
629 Preconditions.checkArgument(false, "Gateway IP address " + strGatewayIp
630 + " is not in subnet range " + subnetCidr);
633 ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
634 return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
637 public static String validateTunnelType(String tunnelType) {
638 if (tunnelType == null) {
639 tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
641 tunnelType = StringUtils.upperCase(tunnelType);
642 String error = "Invalid tunnel type. Valid values: "
643 + ITMConstants.TUNNEL_TYPE_VXLAN + " | " + ITMConstants.TUNNEL_TYPE_GRE;
644 Preconditions.checkArgument(ITMConstants.TUNNEL_TYPE_VXLAN.equals(tunnelType)
645 || ITMConstants.TUNNEL_TYPE_GRE.equals(tunnelType), error);
650 private static List<BigInteger> getConflictingDpnsAlreadyConfiguredWithTz(String schemaName, String tzone,
651 List<BigInteger> lstDpns,
652 List<VtepConfigSchema> existingSchemas) {
653 List<BigInteger> lstConflictingDpns = new ArrayList<>();
654 for (VtepConfigSchema schema : emptyIfNull(existingSchemas)) {
655 if (!StringUtils.equalsIgnoreCase(schemaName, schema.getSchemaName())
656 && StringUtils.equals(schema.getTransportZoneName(), tzone)) {
657 lstConflictingDpns = new ArrayList<>(getDpnIdList(schema.getDpnIds()));
658 lstConflictingDpns.retainAll(lstDpns);
659 if (!lstConflictingDpns.isEmpty()) {
664 return lstConflictingDpns;
667 public static VtepConfigSchema constructVtepConfigSchema(String schemaName, String portName, Integer vlanId,
668 String subnetMask, String gatewayIp, String transportZone,
669 String tunnelType, List<BigInteger> dpnIds,
670 String excludeIpFilter) {
671 IpAddress gatewayIpObj = StringUtils.isBlank(gatewayIp) ? null : new IpAddress(gatewayIp.toCharArray());
672 IpPrefix subnet = StringUtils.isBlank(subnetMask) ? null : new IpPrefix(subnetMask.toCharArray());
673 Class<? extends TunnelTypeBase> tunType ;
674 if (tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN)) {
675 tunType = TunnelTypeVxlan.class ;
677 tunType = TunnelTypeGre.class ;
679 VtepConfigSchemaBuilder schemaBuilder = new VtepConfigSchemaBuilder().setSchemaName(schemaName)
680 .setPortName(portName).setVlanId(vlanId).setSubnet(subnet).setGatewayIp(gatewayIpObj)
681 .setTransportZoneName(transportZone).setTunnelType(tunType).setDpnIds(getDpnIdsListFromBigInt(dpnIds))
682 .setExcludeIpFilter(excludeIpFilter);
683 return schemaBuilder.build();
686 public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
687 final List<IpAddress> lstIpAddress = new ArrayList<>();
688 if (StringUtils.isBlank(excludeIpFilter)) {
691 final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
692 for (String ip : arrIps) {
693 if (StringUtils.countMatches(ip, "-") == 1) {
694 final String[] arrIpRange = StringUtils.split(ip, '-');
695 String strStartIp = StringUtils.trim(arrIpRange[0]);
696 String strEndIp = StringUtils.trim(arrIpRange[1]);
697 Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
698 "Invalid exclude IP filter: invalid IP address value " + strStartIp);
699 Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
700 "Invalid exclude IP filter: invalid IP address value " + strEndIp);
701 Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
702 "Invalid exclude IP filter: IP address [" + strStartIp
703 + "] not in subnet range " + subnetInfo.getCidrSignature());
704 Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
705 "Invalid exclude IP filter: IP address [" + strEndIp
706 + "] not in subnet range " + subnetInfo.getCidrSignature());
707 int startIp = subnetInfo.asInteger(strStartIp);
708 int endIp = subnetInfo.asInteger(strEndIp);
710 Preconditions.checkArgument(startIp < endIp,
711 "Invalid exclude IP filter: Invalid range [" + ip + "] ");
712 for (int iter = startIp; iter <= endIp; iter++) {
713 String ipAddress = ipFormat(toIpArray(iter));
714 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
717 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
723 private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
725 String ip = StringUtils.trim(ipAddress);
726 Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
727 "Invalid exclude IP filter: invalid IP address value " + ip);
728 Preconditions.checkArgument(subnetInfo.isInRange(ip),
729 "Invalid exclude IP filter: IP address [" + ip + "] not in subnet range "
730 + subnetInfo.getCidrSignature());
731 lstIpAddress.add(new IpAddress(ip.toCharArray()));
734 private static int[] toIpArray(int val) {
735 int[] ret = new int[4];
736 for (int iter = 3; iter >= 0; --iter) {
737 ret[iter] |= val >>> 8 * (3 - iter) & 0xff;
742 private static String ipFormat(int[] octets) {
743 StringBuilder str = new StringBuilder();
744 for (int iter = 0; iter < octets.length; ++iter) {
745 str.append(octets[iter]);
746 if (iter != octets.length - 1) {
750 return str.toString();
753 public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd,
754 List<BigInteger> lstDpnsForDelete,
755 IITMProvider itmProvider) {
756 Preconditions.checkArgument(StringUtils.isNotBlank(schemaName));
757 if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty())
758 && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) {
759 Preconditions.checkArgument(false,
760 "DPN ID list for add | delete is null or empty in schema " + schemaName);
762 VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName);
763 if (schema == null) {
764 Preconditions.checkArgument(false, "Specified VTEP Schema [" + schemaName
765 + "] doesn't exists!");
767 List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds());
768 if (isNotEmpty(lstDpnsForAdd)) {
769 // if (isNotEmpty(existingDpnIds)) {
770 List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds);
771 lstAlreadyExistingDpns.retainAll(lstDpnsForAdd);
772 Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(),
773 "DPN ID's " + lstAlreadyExistingDpns
774 + " already exists in VTEP schema [" + schemaName + "]");
776 if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
777 validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd, itmProvider.getAllVtepConfigSchemas());
780 if (isNotEmpty(lstDpnsForDelete)) {
781 if (existingDpnIds == null || existingDpnIds.isEmpty()) {
782 String builder = "DPN ID's " + lstDpnsForDelete
783 + " specified for delete from VTEP schema [" + schemaName
784 + "] are not configured in the schema.";
785 Preconditions.checkArgument(false, builder);
786 } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) {
787 List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete);
788 lstConflictingDpns.removeAll(existingDpnIds);
789 String builder = "DPN ID's " + lstConflictingDpns
790 + " specified for delete from VTEP schema [" + schemaName
791 + "] are not configured in the schema.";
792 Preconditions.checkArgument(false, builder);
798 public static String getSubnetCidrAsString(IpPrefix subnet) {
799 return subnet == null ? StringUtils.EMPTY : String.valueOf(subnet.getValue());
802 public static <T> List<T> emptyIfNull(List<T> list) {
803 return list == null ? Collections.emptyList() : list;
806 public static <T> boolean isEmpty(Collection<T> collection) {
807 return collection == null || collection.isEmpty();
810 public static <T> boolean isNotEmpty(Collection<T> collection) {
811 return !isEmpty(collection);
814 public static HwVtep createHwVtepObject(String topoId, String nodeId, IpAddress ipAddress, IpPrefix ipPrefix,
815 IpAddress gatewayIP, int vlanID,
816 Class<? extends TunnelTypeBase> tunneltype, TransportZone transportZone) {
817 HwVtep hwVtep = new HwVtep();
818 hwVtep.setGatewayIP(gatewayIP);
819 hwVtep.setHwIp(ipAddress);
820 hwVtep.setIpPrefix(ipPrefix);
821 hwVtep.setNode_id(nodeId);
822 hwVtep.setTopo_id(topoId);
823 hwVtep.setTransportZone(transportZone.getZoneName());
824 hwVtep.setTunnel_type(tunneltype);
825 hwVtep.setVlanID(vlanID);
829 public static String getHwParentIf(String topoId, String srcNodeid) {
830 return String.format("%s:%s", topoId, srcNodeid);
833 public static <T extends DataObject> void syncWrite(LogicalDatastoreType datastoreType,
834 InstanceIdentifier<T> path, T data, DataBroker broker) {
835 WriteTransaction tx = broker.newWriteOnlyTransaction();
836 tx.put(datastoreType, path, data, true);
837 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
840 } catch (InterruptedException | ExecutionException e) {
841 LOG.error("ITMUtils:SyncWrite , Error writing to datastore (path, data) : ({}, {})", path, data);
842 throw new RuntimeException(e.getMessage());
846 public static List<BigInteger> getDpnIdList(List<DpnIds> dpnIds) {
847 List<BigInteger> dpnList = new ArrayList<>() ;
848 for (DpnIds dpn : dpnIds) {
849 dpnList.add(dpn.getDPN()) ;
854 public static List<DpnIds> getDpnIdsListFromBigInt(List<BigInteger> dpnIds) {
855 List<DpnIds> dpnIdList = new ArrayList<>();
856 DpnIdsBuilder builder = new DpnIdsBuilder();
857 for (BigInteger dpnId : dpnIds) {
858 dpnIdList.add(builder.setKey(new DpnIdsKey(dpnId)).setDPN(dpnId).build());
863 public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
864 .interfaces.state.Interface> buildStateInterfaceId(String interfaceName) {
865 InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
866 .interfaces.state.Interface> idBuilder = InstanceIdentifier.builder(InterfacesState.class)
867 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
868 .interfaces.state.Interface.class,
869 new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
870 .interfaces.state.InterfaceKey(interfaceName));
871 InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
872 .interfaces.state.Interface> id = idBuilder.build();
876 public static Boolean readMonitoringStateFromCache(DataBroker dataBroker) {
877 InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
878 TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache
879 .get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
880 if (tunnelMonitorParams != null) {
881 return tunnelMonitorParams.isEnabled();
883 return ITMConstants.DEFAULT_MONITOR_ENABLED;
887 public static Integer readMonitorIntervalfromCache(DataBroker dataBroker) {
888 InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.create(TunnelMonitorInterval.class);
889 TunnelMonitorInterval tunnelMonitorIOptional = (TunnelMonitorInterval)DataStoreCache
890 .get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"Interval",dataBroker,true);
891 if (tunnelMonitorIOptional != null) {
892 return tunnelMonitorIOptional.getInterval();
898 public static Integer determineMonitorInterval(DataBroker dataBroker) {
899 Integer monitorInterval = ItmUtils.readMonitorIntervalfromCache(dataBroker);
900 LOG.debug("determineMonitorInterval: monitorInterval from DS = {}", monitorInterval);
901 if (monitorInterval == null) {
902 Class<? extends TunnelMonitoringTypeBase> monitorProtocol = determineMonitorProtocol(dataBroker);
903 if (monitorProtocol.isAssignableFrom(TunnelMonitoringTypeBfd.class)) {
904 monitorInterval = ITMConstants.BFD_DEFAULT_MONITOR_INTERVAL;
906 monitorInterval = ITMConstants.DEFAULT_MONITOR_INTERVAL;
909 LOG.debug("determineMonitorInterval: monitorInterval = {}", monitorInterval);
910 InstanceIdentifier<TunnelMonitorInterval> iid = InstanceIdentifier.builder(TunnelMonitorInterval.class).build();
911 TunnelMonitorInterval intervalBuilder = new TunnelMonitorIntervalBuilder().setInterval(monitorInterval).build();
912 ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, intervalBuilder, dataBroker,
913 ItmUtils.DEFAULT_CALLBACK);
914 return monitorInterval;
917 public static List<String> getInternalTunnelInterfaces(DataBroker dataBroker) {
918 List<String> tunnelList = new ArrayList<>();
919 Collection<String> internalInterfaces = itmCache.getAllInternalInterfaces();
920 if (internalInterfaces == null) {
921 updateTunnelsCache(dataBroker);
922 internalInterfaces = itmCache.getAllInternalInterfaces();
924 LOG.debug("ItmUtils.getTunnelList Cache Internal Interfaces size: {} ", internalInterfaces.size());
925 if (internalInterfaces != null) {
926 tunnelList.addAll(internalInterfaces);
928 LOG.trace("ItmUtils.getTunnelList Internal: {}", tunnelList);
932 public static List<String> getTunnelsofTzone(List<HwVtep> hwVteps, String tzone, DataBroker dataBroker,
933 Boolean hwVtepsExist) {
935 List<String> tunnels = new ArrayList<>();
936 InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class)
937 .child(TransportZone.class, new TransportZoneKey(tzone)).build();
938 Optional<TransportZone> transportZoneOptional =
939 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
940 if (transportZoneOptional.isPresent()) {
941 TransportZone transportZone = transportZoneOptional.get();
942 Class<? extends TunnelTypeBase> tunType = transportZone.getTunnelType();
943 if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
944 for (Subnets sub : transportZone.getSubnets()) {
945 if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
946 for (Vteps vtepLocal : sub.getVteps()) {
947 for (Vteps vtepRemote : sub.getVteps()) {
948 if (!vtepLocal.equals(vtepRemote)) {
949 InternalTunnelKey key = new InternalTunnelKey(vtepRemote.getDpnId(),
950 vtepLocal.getDpnId(), tunType);
951 InstanceIdentifier<InternalTunnel> intIID =
952 InstanceIdentifier.builder(TunnelList.class)
953 .child(InternalTunnel.class, key).build();
954 Optional<InternalTunnel> tunnelsOptional =
955 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
956 if (tunnelsOptional.isPresent()) {
957 List<String> tunnelInterfaceNames = tunnelsOptional
958 .get().getTunnelInterfaceNames();
959 if (tunnelInterfaceNames != null && !tunnelInterfaceNames.isEmpty()) {
960 String tunnelInterfaceName = tunnelInterfaceNames.get(0);
961 LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
962 tunnels.add(tunnelInterfaceName);
967 if (hwVteps != null && !hwVteps.isEmpty()) {
968 for (HwVtep hwVtep : hwVteps) {
969 tunnels.add(getExtTunnel(hwVtep.getNode_id(), vtepLocal.getDpnId().toString(),
970 tunType, dataBroker));
971 tunnels.add(getExtTunnel(vtepLocal.getDpnId().toString(), hwVtep.getNode_id(),
972 tunType, dataBroker));
980 for (HwVtep hwVtep : hwVteps) {
981 for (HwVtep hwVtepOther : hwVteps) {
982 if (!hwVtep.getHwIp().equals(hwVtepOther.getHwIp())) {
983 tunnels.add(getExtTunnel(hwVtep.getNode_id(), hwVtepOther.getNode_id(),
984 tunType, dataBroker));
985 tunnels.add(getExtTunnel(hwVtepOther.getNode_id(), hwVtep.getNode_id(),
986 tunType, dataBroker));
995 public static List<String> getInternalTunnelsofTzone(String tzone, DataBroker dataBroker) {
996 List<String> tunnels = new ArrayList<>();
997 LOG.trace("Getting internal tunnels of {}",tzone);
998 InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class)
999 .child(TransportZone.class, new TransportZoneKey(tzone)).build();
1000 Optional<TransportZone> transportZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION,
1002 if (transportZoneOptional.isPresent()) {
1003 TransportZone transportZone = transportZoneOptional.get();
1004 if (transportZone.getSubnets() != null && !transportZone.getSubnets().isEmpty()) {
1005 for (Subnets sub : transportZone.getSubnets()) {
1006 if (sub.getVteps() != null && !sub.getVteps().isEmpty()) {
1007 for (Vteps vtepLocal : sub.getVteps()) {
1008 for (Vteps vtepRemote : sub.getVteps()) {
1009 if (!vtepLocal.equals(vtepRemote)) {
1010 InternalTunnelKey key =
1011 new InternalTunnelKey(vtepRemote.getDpnId(), vtepLocal.getDpnId(),
1012 transportZone.getTunnelType());
1013 InstanceIdentifier<InternalTunnel> intIID =
1014 InstanceIdentifier.builder(TunnelList.class)
1015 .child(InternalTunnel.class, key).build();
1016 Optional<InternalTunnel> tunnelsOptional =
1017 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
1018 if (tunnelsOptional.isPresent()) {
1019 List<String> tunnelInterfaceNames = tunnelsOptional.get()
1020 .getTunnelInterfaceNames();
1021 if (tunnelInterfaceNames != null && !tunnelInterfaceNames.isEmpty()) {
1022 String tunnelInterfaceName = tunnelInterfaceNames.get(0);
1023 LOG.trace("Internal Tunnel added {}", tunnelInterfaceName);
1024 tunnels.add(tunnelInterfaceName);
1037 private static String getExtTunnel(String nodeId, String dpId,Class<? extends TunnelTypeBase> tunType, DataBroker
1039 LOG.trace("getting ext tunnel for {} and dpId {}",nodeId,dpId);
1040 ExternalTunnelKey key = getExternalTunnelKey(dpId, nodeId, tunType);
1041 InstanceIdentifier<ExternalTunnel> intIID = InstanceIdentifier.builder(ExternalTunnelList.class)
1042 .child(ExternalTunnel.class, key).build();
1043 Optional<ExternalTunnel> tunnelsOptional =
1044 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, intIID, dataBroker);
1045 if (tunnelsOptional.isPresent()) {
1046 String tunnelInterfaceName = tunnelsOptional.get().getTunnelInterfaceName();
1047 LOG.trace("ext tunnel returned {} ", tunnelInterfaceName);
1048 return tunnelInterfaceName;
1053 public static ExternalTunnelKey getExternalTunnelKey(String dst , String src,
1054 Class<? extends TunnelTypeBase> tunType) {
1055 if (src.indexOf("physicalswitch") > 0) {
1056 src = src.substring(0, src.indexOf("physicalswitch") - 1);
1058 if (dst.indexOf("physicalswitch") > 0) {
1059 dst = dst.substring(0, dst.indexOf("physicalswitch") - 1);
1061 return new ExternalTunnelKey(dst, src, tunType);
1064 public static List<TunnelEndPoints> getTEPsForDpn(BigInteger srcDpn, List<DPNTEPsInfo> dpnList) {
1065 for (DPNTEPsInfo dpn : dpnList) {
1066 if (dpn.getDPNID().equals(srcDpn)) {
1067 return dpn.getTunnelEndPoints() ;
1073 public static TunnelList getAllInternalTunnels(DataBroker broker) {
1074 InstanceIdentifier<TunnelList> tunnelListInstanceIdentifier =
1075 InstanceIdentifier.builder(TunnelList.class).build();
1076 return read(LogicalDatastoreType.CONFIGURATION, tunnelListInstanceIdentifier, broker).orNull();
1079 public static List<InternalTunnel> getAllInternalTunnels(DataBroker dataBroker,
1080 LogicalDatastoreType datastoreType) {
1081 List<InternalTunnel> result = null;
1082 InstanceIdentifier<TunnelList> iid = InstanceIdentifier.builder(TunnelList.class).build();
1083 Optional<TunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1084 if (tunnelList.isPresent()) {
1085 result = tunnelList.get().getInternalTunnel();
1087 if (result == null) {
1088 result = Collections.emptyList();
1093 public static InternalTunnel getInternalTunnel(String interfaceName, DataBroker broker) {
1094 InternalTunnel internalTunnel = null;
1095 internalTunnel = itmCache.getInternalTunnel(interfaceName);
1096 if (internalTunnel == null) {
1097 updateTunnelsCache(broker);
1098 internalTunnel = itmCache.getInternalTunnel(interfaceName);
1100 return internalTunnel;
1103 public static ExternalTunnel getExternalTunnel(String interfaceName, DataBroker broker) {
1104 ExternalTunnel externalTunnel = null;
1105 externalTunnel = itmCache.getExternalTunnel(interfaceName);
1106 if (externalTunnel == null) {
1107 updateTunnelsCache(broker);
1108 externalTunnel = itmCache.getExternalTunnel(interfaceName);
1110 return externalTunnel;
1113 public static List<ExternalTunnel> getAllExternalTunnels(DataBroker broker) {
1114 List<ExternalTunnel> result = null;
1115 InstanceIdentifier<ExternalTunnelList> id = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1116 Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, id, broker);
1117 if (tunnelList.isPresent()) {
1118 result = tunnelList.get().getExternalTunnel();
1120 if (result == null) {
1121 result = Collections.emptyList();
1126 public static List<ExternalTunnel> getAllExternalTunnels(DataBroker dataBroker,
1127 LogicalDatastoreType datastoreType) {
1128 List<ExternalTunnel> result = null;
1129 InstanceIdentifier<ExternalTunnelList> iid = InstanceIdentifier.builder(ExternalTunnelList.class).build();
1130 Optional<ExternalTunnelList> tunnelList = read(LogicalDatastoreType.CONFIGURATION, iid, dataBroker);
1131 if (tunnelList.isPresent()) {
1132 result = tunnelList.get().getExternalTunnel();
1134 if (result == null) {
1135 result = Collections.emptyList();
1140 public static String convertTunnelTypetoString(Class<? extends TunnelTypeBase> tunType) {
1141 String tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
1142 if (tunType.equals(TunnelTypeVxlan.class)) {
1143 tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN ;
1144 } else if (tunType.equals(TunnelTypeGre.class)) {
1145 tunnelType = ITMConstants.TUNNEL_TYPE_GRE ;
1146 } else if (tunType.equals(TunnelTypeMplsOverGre.class)) {
1147 tunnelType = ITMConstants.TUNNEL_TYPE_MPLSoGRE;
1148 } else if (tunType.equals(TunnelTypeLogicalGroup.class)) {
1149 tunnelType = ITMConstants.TUNNEL_TYPE_LOGICAL_GROUP_VXLAN;
1155 public static boolean isItmIfType(Class<? extends InterfaceType> ifType) {
1156 return ifType != null && ifType.isAssignableFrom(Tunnel.class);
1159 public static StateTunnelListKey getTunnelStateKey(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf
1160 .interfaces.rev140508.interfaces.state.Interface iface) {
1161 StateTunnelListKey key = null;
1162 if (isItmIfType(iface.getType())) {
1163 key = new StateTunnelListKey(iface.getName());
1168 public static void updateTunnelsCache(DataBroker broker) {
1169 List<InternalTunnel> internalTunnels = getAllInternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
1170 for (InternalTunnel tunnel : internalTunnels) {
1171 itmCache.addInternalTunnel(tunnel);
1173 List<ExternalTunnel> externalTunnels = getAllExternalTunnels(broker, LogicalDatastoreType.CONFIGURATION);
1174 for (ExternalTunnel tunnel : externalTunnels) {
1175 itmCache.addExternalTunnel(tunnel);
1179 public static Interface getInterface(
1180 String name, IInterfaceManager ifaceManager) {
1181 Interface result = itmCache.getInterface(name);
1182 if (result == null) {
1183 result = ifaceManager.getInterfaceInfoFromConfigDataStore(name);
1184 if (result != null) {
1185 itmCache.addInterface(result);
1191 public static StateTunnelList getTunnelState(DataBroker dataBroker, String ifaceName,
1192 InstanceIdentifier<StateTunnelList> stListId) {
1193 StateTunnelList tunnelState = (StateTunnelList)DataStoreCache
1194 .get(ITMConstants.TUNNEL_STATE_CACHE_NAME, ifaceName);
1195 if (tunnelState == null) {
1196 Optional<StateTunnelList> tunnelsState = ItmUtils
1197 .read(LogicalDatastoreType.OPERATIONAL, stListId, dataBroker);
1198 if (tunnelsState.isPresent()) {
1205 public static Class<? extends TunnelMonitoringTypeBase> readMonitoringProtocolFromCache(DataBroker dataBroker) {
1206 InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.create(TunnelMonitorParams.class);
1207 TunnelMonitorParams tunnelMonitorParams = (TunnelMonitorParams) DataStoreCache
1208 .get(ITMConstants.ITM_MONIRORING_PARAMS_CACHE_NAME,iid,"MonitorParams",dataBroker,true);
1209 if (tunnelMonitorParams != null) {
1210 return tunnelMonitorParams.getMonitorProtocol();
1215 public static Class<? extends TunnelMonitoringTypeBase> determineMonitorProtocol(DataBroker dataBroker) {
1216 Class<? extends TunnelMonitoringTypeBase> monitoringProtocol =
1217 ItmUtils.readMonitoringProtocolFromCache(dataBroker);
1218 LOG.debug("determineMonitorProtocol: monitorProtocol from DS = {}", monitoringProtocol);
1219 if (monitoringProtocol == null) {
1220 monitoringProtocol = ITMConstants.DEFAULT_MONITOR_PROTOCOL;
1222 LOG.debug("determineMonitorProtocol: monitorProtocol = {}", monitoringProtocol);
1223 Boolean monitorState = ItmUtils.readMonitoringStateFromCache(dataBroker);
1224 if (monitorState == null) {
1225 monitorState = true;
1227 LOG.debug("determineMonitorProtocol: monitorState = {}", monitorState);
1228 InstanceIdentifier<TunnelMonitorParams> iid = InstanceIdentifier.builder(TunnelMonitorParams.class).build();
1229 TunnelMonitorParams protocolBuilder = new TunnelMonitorParamsBuilder().setEnabled(monitorState)
1230 .setMonitorProtocol(monitoringProtocol).build();
1231 ItmUtils.asyncUpdate(LogicalDatastoreType.OPERATIONAL,iid, protocolBuilder, dataBroker,
1232 ItmUtils.DEFAULT_CALLBACK);
1233 return monitoringProtocol;
1236 public static List<DcGatewayIp> getDcGatewayIpList(DataBroker broker) {
1237 InstanceIdentifier<DcGatewayIpList> dcGatewayIpListid =
1238 InstanceIdentifier.builder(DcGatewayIpList.class).build();
1239 Optional<DcGatewayIpList> dcGatewayIpListConfig =
1240 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, dcGatewayIpListid, broker);
1241 if (dcGatewayIpListConfig.isPresent()) {
1242 DcGatewayIpList containerList = dcGatewayIpListConfig.get();
1243 if (containerList != null) {
1244 return containerList.getDcGatewayIp();
1250 public static boolean falseIfNull(Boolean value) {
1251 return value == null ? false : value;
1254 public static <T> List<T> getIntersection(List<T> list1, List<T> list2) {
1255 List<T> list = new ArrayList<>();
1256 for (T iter : list1) {
1257 if (list2.contains(iter)) {
1261 LOG.debug(" getIntersection - L1 {}, L2 - {}, Intersection - {}", list1, list2, list);
1265 public static void addTransportZoneMembership(List<TzMembership> zones, String zoneName) {
1266 zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());
1269 public static List<TzMembership> createTransportZoneMembership(String zoneName) {
1270 List<TzMembership> zones = new ArrayList<>();
1271 zones.add(new TzMembershipBuilder().setZoneName(zoneName).build());
1276 * Returns the transport zone from Configuration datastore.
1278 * @param tzName transport zone name
1279 * @param dataBroker data broker handle to perform operations on datastore
1280 * @return the TransportZone object in Config DS
1282 // FIXME: Better is to implement cache to avoid datastore read.
1283 public static TransportZone getTransportZoneFromConfigDS(String tzName, DataBroker dataBroker) {
1284 InstanceIdentifier<TransportZone> tzonePath = InstanceIdentifier.builder(TransportZones.class)
1285 .child(TransportZone.class, new TransportZoneKey(tzName)).build();
1286 Optional<TransportZone> transportZoneOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, tzonePath,
1288 if (transportZoneOptional.isPresent()) {
1289 return transportZoneOptional.get();
1295 * Gets the transport zone in TepsNotHosted list in the Configuration Datastore, based on transport zone name.
1297 * @param unknownTz transport zone name
1299 * @param dataBroker data broker handle to perform read operations on config datastore
1301 * @return the TepsNotHostedInTransportZone object in the TepsNotHosted list in Config DS
1303 public static TepsNotHostedInTransportZone getUnknownTransportZoneFromITMConfigDS(
1304 String unknownTz, DataBroker dataBroker) {
1305 InstanceIdentifier<TepsNotHostedInTransportZone> unknownTzPath =
1306 InstanceIdentifier.builder(TransportZones.class)
1307 .child(TepsNotHostedInTransportZone.class,
1308 new TepsNotHostedInTransportZoneKey(unknownTz)).build();
1309 Optional<TepsNotHostedInTransportZone> unknownTzOptional =
1310 ItmUtils.read(LogicalDatastoreType.CONFIGURATION, unknownTzPath, dataBroker);
1311 if (unknownTzOptional.isPresent()) {
1312 return unknownTzOptional.get();
1318 * Gets the bridge datapath ID from Network topology Node's OvsdbBridgeAugmentation, in the Operational DS.
1320 * @param node Network Topology Node
1322 * @param bridge bridge name
1324 * @param dataBroker data broker handle to perform operations on datastore
1326 * @return the datapath ID of bridge in string form
1328 public static String getBridgeDpid(Node node, String bridge, DataBroker dataBroker) {
1329 OvsdbBridgeAugmentation ovsdbBridgeAugmentation = null;
1330 Node bridgeNode = null;
1331 String datapathId = null;
1333 NodeId ovsdbNodeId = node.getKey().getNodeId();
1335 NodeId brNodeId = new NodeId(ovsdbNodeId.getValue()
1336 + "/" + ITMConstants.BRIDGE_URI_PREFIX + "/" + bridge);
1338 InstanceIdentifier<Node> bridgeIid =
1340 .create(NetworkTopology.class)
1341 .child(Topology.class, new TopologyKey(IfmConstants.OVSDB_TOPOLOGY_ID))
1342 .child(Node.class,new NodeKey(brNodeId));
1344 Optional<Node> opBridgeNode = ItmUtils.read(LogicalDatastoreType.OPERATIONAL, bridgeIid, dataBroker);
1346 if (opBridgeNode.isPresent()) {
1347 bridgeNode = opBridgeNode.get();
1349 if (bridgeNode != null) {
1350 ovsdbBridgeAugmentation = bridgeNode.getAugmentation(OvsdbBridgeAugmentation.class);
1353 if (ovsdbBridgeAugmentation != null && ovsdbBridgeAugmentation.getDatapathId() != null) {
1354 datapathId = ovsdbBridgeAugmentation.getDatapathId().getValue();
1360 * Gets the Network topology Node from Operational Datastore
1361 * based on Bridge Augmentation.
1363 * @param bridgeAugmentation bridge augmentation of OVSDB node
1365 * @param dataBroker data broker handle to perform operations on datastore
1367 * @return the Network Topology Node i.e. OVSDB node which is managing the specified bridge
1369 public static Node getOvsdbNode(OvsdbBridgeAugmentation bridgeAugmentation,
1370 DataBroker dataBroker) {
1371 Node ovsdbNode = null;
1372 Optional<Node> opOvsdbNode = null;
1373 if (bridgeAugmentation != null) {
1374 InstanceIdentifier<Node> ovsdbNodeIid =
1375 (InstanceIdentifier<Node>) bridgeAugmentation.getManagedBy().getValue();
1376 opOvsdbNode = ItmUtils.read(LogicalDatastoreType.OPERATIONAL, ovsdbNodeIid, dataBroker);
1378 if (opOvsdbNode.isPresent()) {
1379 ovsdbNode = opOvsdbNode.get();
1385 * Gets the bridge datapath ID in string form from
1386 * Network topology Node's OvsdbBridgeAugmentation in the Operational DS.
1388 * @param augmentedNode Ovsdb Augmented Network Topology Node
1390 * @return the datapath ID of bridge in string form
1392 public static String getStrDatapathId(OvsdbBridgeAugmentation augmentedNode) {
1393 String datapathId = null;
1394 if (augmentedNode != null && augmentedNode.getDatapathId() != null) {
1395 datapathId = augmentedNode.getDatapathId().getValue();
1401 * Returns the dummy subnet (255.255.255.255/32) as IpPrefix object.
1403 * @return the dummy subnet (255.255.255.255/32) in IpPrefix object
1405 public static IpPrefix getDummySubnet() {
1406 return DUMMY_IP_PREFIX;
1410 * Deletes the transport zone from Configuration datastore.
1412 * @param tzName transport zone name
1413 * @param dataBroker data broker handle to perform operations on datastore
1415 public static void deleteTransportZoneFromConfigDS(String tzName, DataBroker dataBroker) {
1416 // check whether transport-zone exists in config DS.
1417 TransportZone transportZoneFromConfigDS = ItmUtils.getTransportZoneFromConfigDS(tzName, dataBroker);
1418 if (transportZoneFromConfigDS != null) {
1419 // it exists, delete default-TZ now
1420 InstanceIdentifier<TransportZone> path = InstanceIdentifier.builder(TransportZones.class)
1421 .child(TransportZone.class,
1422 new TransportZoneKey(tzName)).build();
1423 LOG.debug("Removing {} transport-zone from config DS.", tzName);
1425 SingleTransactionDataBroker.syncDelete(dataBroker, LogicalDatastoreType.CONFIGURATION, path);
1426 } catch (TransactionCommitFailedException e) {
1427 LOG.error("deleteTransportZoneFromConfigDS failed. {} could not be deleted.", tzName, e);
1433 * Validates the tunnelType argument and returnsTunnelTypeBase class object
1434 * corresponding to tunnelType obtained in String format.
1436 * @param tunnelType type of tunnel in string form
1438 * @return tunnel-type in TunnelTypeBase object
1440 public static Class<? extends TunnelTypeBase> getTunnelType(String tunnelType) {
1441 // validate tunnelType string, in case it is NULL or empty, then
1442 // take VXLAN tunnel type by default
1443 if (tunnelType == null || tunnelType.isEmpty()) {
1444 return TUNNEL_TYPE_MAP.get(ITMConstants.TUNNEL_TYPE_VXLAN);
1445 } else if (!tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN)
1446 && !tunnelType.equals(ITMConstants.TUNNEL_TYPE_GRE)) {
1447 // if tunnel type is some incorrect value, then
1448 // take VXLAN tunnel type by default
1449 return TUNNEL_TYPE_MAP.get(ITMConstants.TUNNEL_TYPE_VXLAN);
1452 // return TunnelTypeBase object corresponding to tunnel-type
1453 return TUNNEL_TYPE_MAP.get(tunnelType);
1456 public static List<TzMembership> removeTransportZoneMembership(TunnelEndPoints endPts, List<TzMembership> zones) {
1457 LOG.trace(" RemoveTransportZoneMembership TEPs {}, Membership to be removed {} ", endPts, zones);
1458 List<TzMembership> existingTzList = new ArrayList<>(endPts.getTzMembership()) ;
1459 for (TzMembership membership : zones) {
1460 existingTzList.remove(new TzMembershipBuilder().setZoneName(membership.getZoneName()).build());
1462 LOG.debug("Modified Membership List {}", existingTzList);
1463 return existingTzList;
1466 public static List<TzMembership> getOriginalTzMembership(TunnelEndPoints srcTep, BigInteger dpnId,
1467 List<DPNTEPsInfo> meshedDpnList) {
1468 LOG.trace("Original Membership for source DPN {}, source TEP {}", dpnId, srcTep);
1469 for (DPNTEPsInfo dstDpn : meshedDpnList) {
1470 if (dpnId.equals(dstDpn.getDPNID())) {
1471 List<TunnelEndPoints> endPts = dstDpn.getTunnelEndPoints();
1472 for (TunnelEndPoints tep : endPts) {
1473 if (tep.getIpAddress().equals(srcTep.getIpAddress())) {
1474 LOG.debug("Original Membership size " + tep.getTzMembership().size()) ;
1475 return tep.getTzMembership();
1483 public static StateTunnelList buildStateTunnelList(StateTunnelListKey tlKey, String name, boolean state,
1484 TunnelOperStatus tunOpStatus, IInterfaceManager ifaceManager,
1485 DataBroker broker) {
1486 StateTunnelListBuilder stlBuilder = new StateTunnelListBuilder();
1487 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface iface =
1488 ItmUtils.getInterface(name, ifaceManager);
1489 IfTunnel ifTunnel = iface.getAugmentation(IfTunnel.class);
1490 ParentRefs parentRefs = iface.getAugmentation(ParentRefs.class);
1491 if (ifTunnel == null && parentRefs == null) {
1494 DstInfoBuilder dstInfoBuilder = new DstInfoBuilder();
1495 SrcInfoBuilder srcInfoBuilder = new SrcInfoBuilder();
1496 dstInfoBuilder.setTepIp(ifTunnel.getTunnelDestination());
1497 srcInfoBuilder.setTepIp(ifTunnel.getTunnelSource());
1498 // TODO: Add/Improve logic for device type
1499 InternalTunnel internalTunnel = ItmUtils.itmCache.getInternalTunnel(name);
1500 ExternalTunnel externalTunnel = ItmUtils.itmCache.getExternalTunnel(name);
1501 if (internalTunnel == null && externalTunnel == null) {
1502 // both not present in cache. let us update and try again.
1503 ItmUtils.updateTunnelsCache(broker);
1504 internalTunnel = ItmUtils.itmCache.getInternalTunnel(name);
1505 externalTunnel = ItmUtils.itmCache.getExternalTunnel(name);
1507 if (internalTunnel != null) {
1508 srcInfoBuilder.setTepDeviceId(internalTunnel.getSourceDPN().toString())
1509 .setTepDeviceType(TepTypeInternal.class);
1510 dstInfoBuilder.setTepDeviceId(internalTunnel.getDestinationDPN().toString())
1511 .setTepDeviceType(TepTypeInternal.class);
1512 stlBuilder.setTransportType(internalTunnel.getTransportType());
1513 } else if (externalTunnel != null) {
1514 ExternalTunnel tunnel = ItmUtils.itmCache.getExternalTunnel(name);
1515 srcInfoBuilder.setTepDeviceId(tunnel.getSourceDevice())
1516 .setTepDeviceType(getDeviceType(tunnel.getSourceDevice()));
1517 dstInfoBuilder.setTepDeviceId(tunnel.getDestinationDevice())
1518 .setTepDeviceType(getDeviceType(tunnel.getDestinationDevice()))
1519 .setTepIp(ifTunnel.getTunnelDestination());
1520 stlBuilder.setTransportType(tunnel.getTransportType());
1522 stlBuilder.setKey(tlKey).setTunnelInterfaceName(name).setOperState(tunOpStatus).setTunnelState(state)
1523 .setDstInfo(dstInfoBuilder.build()).setSrcInfo(srcInfoBuilder.build());
1524 return stlBuilder.build();
1527 public static Class<? extends TepTypeBase> getDeviceType(String device) {
1528 if (device.startsWith("hwvtep")) {
1529 return TepTypeHwvtep.class;
1530 } else if (device.contains("IpAddress")) {
1531 return TepTypeExternal.class;
1533 return TepTypeInternal.class;
1537 public static InstanceIdentifier<StateTunnelList> buildStateTunnelListId(StateTunnelListKey tlKey) {
1538 return InstanceIdentifier.builder(TunnelsState.class)
1539 .child(StateTunnelList.class, tlKey).build();
1542 public static Optional<InternalTunnel> getInternalTunnelFromDS(BigInteger srcDpn, BigInteger destDpn,
1543 Class<? extends TunnelTypeBase> type,
1544 DataBroker dataBroker) {
1545 InstanceIdentifier<InternalTunnel> pathLogicTunnel = InstanceIdentifier.create(TunnelList.class)
1546 .child(InternalTunnel.class,
1547 new InternalTunnelKey(destDpn, srcDpn, type));
1548 //TODO: need to be replaced by cached copy
1549 return ItmUtils.read(LogicalDatastoreType.CONFIGURATION, pathLogicTunnel, dataBroker);
1552 public static boolean isTunnelAggregationUsed(Class<? extends TunnelTypeBase> tunType) {
1553 return (ItmTunnelAggregationHelper.isTunnelAggregationEnabled()
1554 && (tunType.isAssignableFrom(TunnelTypeVxlan.class)
1555 || tunType.isAssignableFrom(TunnelTypeLogicalGroup.class)));