2 * Copyright (c) 2015, 2016 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.vpnservice.itm.impl;
10 import java.math.BigInteger;
11 import java.net.InetAddress;
12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.List;
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.Future;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import org.apache.commons.lang3.StringUtils;
22 import org.apache.commons.net.util.SubnetUtils;
23 import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
24 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
25 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
26 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
29 import org.opendaylight.vpnservice.itm.api.IITMProvider;
30 import org.opendaylight.vpnservice.itm.confighelpers.HwVtep;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.Tunnel;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.config.rev151102.VtepConfigSchemas;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.config.rev151102.VtepIpPools;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.config.rev151102.vtep.config.schemas.VtepConfigSchema;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.config.rev151102.vtep.config.schemas.VtepConfigSchemaBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.config.rev151102.vtep.config.schemas.VtepConfigSchemaKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.config.rev151102.vtep.ip.pools.VtepIpPool;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.config.rev151102.vtep.ip.pools.VtepIpPoolKey;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.AllocateIdInput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.AllocateIdInputBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.AllocateIdOutput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.IdManagerService;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.ReleaseIdInput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.ReleaseIdInputBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.*;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.interfaces._interface.NodeIdentifier;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.interfaces._interface.NodeIdentifierBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.interfaces._interface.NodeIdentifierKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.DpnEndpoints;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.DpnEndpointsBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.dpn.endpoints.DPNTEPsInfo;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.dpn.endpoints.DPNTEPsInfoBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.dpn.endpoints.DPNTEPsInfoKey;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.dpn.endpoints.dpn.teps.info.TunnelEndPoints;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.dpn.endpoints.dpn.teps.info.TunnelEndPointsBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.dpn.endpoints.dpn.teps.info.TunnelEndPointsKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.external.tunnel.list.ExternalTunnel;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.external.tunnel.list.ExternalTunnelBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.external.tunnel.list.ExternalTunnelKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.tunnel.list.InternalTunnel;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.tunnel.list.InternalTunnelBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.op.rev150701.tunnel.list.InternalTunnelKey;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.TunnelTypeGre;
66 import org.opendaylight.vpnservice.mdsalutil.interfaces.IMdsalApiManager;
67 import org.opendaylight.vpnservice.itm.globals.ITMConstants;
68 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil;
69 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
70 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
71 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType;
72 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.config.rev151102.vtep.config.schemas.vtep.config.schema.DpnIds ;
76 //import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice._interface.service.rev150602._interface.service.info.ServiceInfo;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rev150701.transport.zones.TransportZone;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.config.rev151102.vtep.config.schemas.vtep.config.schema.DpnIdsBuilder;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.config.rev151102.vtep.config.schemas.vtep.config.schema.DpnIdsKey;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.config.rev151102.vtep.config.schemas.vtep.config.schema.DpnIds;
81 import org.opendaylight.yangtools.yang.binding.DataObject;
82 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
83 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
85 import org.opendaylight.yangtools.yang.common.RpcResult;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
88 import org.opendaylight.vpnservice.mdsalutil.ActionInfo;
89 import org.opendaylight.vpnservice.mdsalutil.ActionType;
90 import org.opendaylight.vpnservice.mdsalutil.FlowEntity;
91 import org.opendaylight.vpnservice.mdsalutil.InstructionInfo;
92 import org.opendaylight.vpnservice.mdsalutil.InstructionType;
93 import org.opendaylight.vpnservice.mdsalutil.MatchFieldType;
94 import org.opendaylight.vpnservice.mdsalutil.MatchInfo;
95 import org.opendaylight.vpnservice.mdsalutil.MetaDataUtil;
96 import org.opendaylight.vpnservice.mdsalutil.NwConstants;
98 import com.google.common.base.Optional;
99 import com.google.common.base.Preconditions;
100 import com.google.common.net.InetAddresses;
101 import com.google.common.util.concurrent.FutureCallback;
102 import com.google.common.util.concurrent.Futures;
104 public class ItmUtils {
106 public static final String DUMMY_IP_ADDRESS = "0.0.0.0";
107 public static final String TUNNEL_TYPE_VXLAN = "VXLAN";
108 public static final String TUNNEL_TYPE_GRE = "GRE";
109 public static final String TUNNEL = "TUNNEL";
111 private static final Logger LOG = LoggerFactory.getLogger(ItmUtils.class);
113 public static final FutureCallback<Void> DEFAULT_CALLBACK = new FutureCallback<Void>() {
114 public void onSuccess(Void result) {
115 LOG.debug("Success in Datastore write operation");
118 public void onFailure(Throwable error) {
119 LOG.error("Error in Datastore write operation", error);
123 public static <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
124 InstanceIdentifier<T> path, DataBroker broker) {
126 ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
128 Optional<T> result = Optional.absent();
130 result = tx.read(datastoreType, path).get();
131 } catch (Exception e) {
132 throw new RuntimeException(e);
138 public static <T extends DataObject> void asyncWrite(LogicalDatastoreType datastoreType,
139 InstanceIdentifier<T> path, T data, DataBroker broker, FutureCallback<Void> callback) {
140 WriteTransaction tx = broker.newWriteOnlyTransaction();
141 tx.put(datastoreType, path, data, true);
142 Futures.addCallback(tx.submit(), callback);
145 public static <T extends DataObject> void asyncUpdate(LogicalDatastoreType datastoreType,
146 InstanceIdentifier<T> path, T data, DataBroker broker, FutureCallback<Void> callback) {
147 WriteTransaction tx = broker.newWriteOnlyTransaction();
148 tx.merge(datastoreType, path, data, true);
149 Futures.addCallback(tx.submit(), callback);
152 public static <T extends DataObject> void asyncDelete(LogicalDatastoreType datastoreType,
153 InstanceIdentifier<T> path, DataBroker broker, FutureCallback<Void> callback) {
154 WriteTransaction tx = broker.newWriteOnlyTransaction();
155 tx.delete(datastoreType, path);
156 Futures.addCallback(tx.submit(), callback);
158 public static <T extends DataObject> void asyncBulkRemove(final DataBroker broker,final LogicalDatastoreType datastoreType,
159 List<InstanceIdentifier<T>> pathList, FutureCallback<Void> callback) {
160 if (!pathList.isEmpty()) {
161 WriteTransaction tx = broker.newWriteOnlyTransaction();
162 for (InstanceIdentifier<T> path : pathList) {
163 tx.delete(datastoreType, path);
165 Futures.addCallback(tx.submit(), callback);
169 public static String getInterfaceName(final BigInteger datapathid, final String portName, final Integer vlanId) {
170 return String.format("%s:%s:%s", datapathid, portName, vlanId);
173 public static BigInteger getDpnIdFromInterfaceName(String interfaceName) {
174 String[] dpnStr = interfaceName.split(":");
175 BigInteger dpnId = new BigInteger(dpnStr[0]);
179 public static String getTrunkInterfaceName(IdManagerService idManager, String parentInterfaceName, String localHostName, String remoteHostName) {
180 String trunkInterfaceName = String.format("%s:%s:%s", parentInterfaceName, localHostName, remoteHostName);
181 trunkInterfaceName = String.format("%s:%s", TUNNEL, getUniqueId(idManager, trunkInterfaceName));
182 return trunkInterfaceName;
185 public static void releaseIdForTrunkInterfaceName(IdManagerService idManager, String parentInterfaceName, String localHostName, String remoteHostName) {
186 String trunkInterfaceName = String.format("%s:%s:%s", parentInterfaceName, localHostName, remoteHostName);
187 LOG.trace("Releasing Id for trunkInterface - {}", trunkInterfaceName );
188 releaseId(idManager, trunkInterfaceName) ;
191 public static InetAddress getInetAddressFromIpAddress(IpAddress ip) {
192 return InetAddresses.forString(ip.getIpv4Address().getValue());
195 public static InstanceIdentifier<DPNTEPsInfo> getDPNTEPInstance(BigInteger dpIdKey) {
196 InstanceIdentifier.InstanceIdentifierBuilder<DPNTEPsInfo> dpnTepInfoBuilder =
197 InstanceIdentifier.builder(DpnEndpoints.class).child(DPNTEPsInfo.class, new DPNTEPsInfoKey(dpIdKey));
198 InstanceIdentifier<DPNTEPsInfo> dpnInfo = dpnTepInfoBuilder.build();
202 public static DPNTEPsInfo createDPNTepInfo(BigInteger dpId, List<TunnelEndPoints> endpoints) {
204 return new DPNTEPsInfoBuilder().setKey(new DPNTEPsInfoKey(dpId)).setTunnelEndPoints(endpoints).build();
207 public static TunnelEndPoints createTunnelEndPoints(BigInteger dpnId, IpAddress ipAddress, String portName, int vlanId,
208 IpPrefix prefix, IpAddress gwAddress, String zoneName, Class<? extends TunnelTypeBase> tunnel_type) {
209 // when Interface Mgr provides support to take in Dpn Id
210 return new TunnelEndPointsBuilder().setKey(new TunnelEndPointsKey(ipAddress, portName, vlanId))
211 .setSubnetMask(prefix).setGwIpAddress(gwAddress).setTransportZone(zoneName)
212 .setInterfaceName(ItmUtils.getInterfaceName(dpnId, portName, vlanId)).setTunnelType(tunnel_type).build();
215 public static DpnEndpoints createDpnEndpoints(List<DPNTEPsInfo> dpnTepInfo) {
216 return new DpnEndpointsBuilder().setDPNTEPsInfo(dpnTepInfo).build();
219 public static InstanceIdentifier<Interface> buildId(String interfaceName) {
220 InstanceIdentifierBuilder<Interface> idBuilder =
221 InstanceIdentifier.builder(Interfaces.class).child(Interface.class, new InterfaceKey(interfaceName));
222 InstanceIdentifier<Interface> id = idBuilder.build();
226 public static Interface buildTunnelInterface(BigInteger dpn, String ifName, String desc, boolean enabled, Class<? extends TunnelTypeBase> tunType,
227 IpAddress localIp, IpAddress remoteIp, IpAddress gatewayIp,Integer vlanId, boolean internal, boolean monitorEnabled, Long monitorInterval) {
228 InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(ifName)).setName(ifName)
229 .setDescription(desc).setEnabled(enabled).setType(Tunnel.class);
230 ParentRefs parentRefs = new ParentRefsBuilder().setDatapathNodeIdentifier(dpn).build();
231 builder.addAugmentation(ParentRefs.class, parentRefs);
233 IfL2vlan l2vlan = new IfL2vlanBuilder().setVlanId(new VlanId(vlanId)).build();
234 builder.addAugmentation(IfL2vlan.class, l2vlan);
236 //use default monitoring value from Global Constants
237 Long monitoringInterval = 10000L;
238 if(monitorInterval!= null)
239 monitoringInterval = monitorInterval;
240 IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(remoteIp).setTunnelGateway(gatewayIp).setTunnelSource(localIp)
241 .setTunnelInterfaceType(tunType).setInternal(internal).setMonitorEnabled(monitorEnabled).setMonitorInterval(monitoringInterval).build();
242 builder.addAugmentation(IfTunnel.class, tunnel);
243 return builder.build();
246 public static Interface buildHwTunnelInterface(String tunnelIfName, String desc , boolean enabled, String topo_id, String node_id,
247 Class<? extends TunnelTypeBase> tunType, IpAddress srcIp , IpAddress destIp, IpAddress gWIp,
248 boolean monitor_enabled
250 InterfaceBuilder builder = new InterfaceBuilder().setKey(new InterfaceKey(tunnelIfName)).setName(tunnelIfName).setDescription(desc).
251 setEnabled(enabled).setType(Tunnel.class);
252 List<NodeIdentifier> nodeIds = new ArrayList<NodeIdentifier>();
253 NodeIdentifier hWnode = new NodeIdentifierBuilder().setKey(new NodeIdentifierKey(topo_id)).setTopologyId(
255 setNodeId(node_id).build();
257 ParentRefs parent = new ParentRefsBuilder().setNodeIdentifier(nodeIds).build();
258 builder.addAugmentation(ParentRefs.class , parent);
259 IfTunnel tunnel = new IfTunnelBuilder().setTunnelDestination(destIp).setTunnelGateway(gWIp).setTunnelSource(
260 srcIp).setMonitorEnabled(monitor_enabled).setTunnelInterfaceType(tunType).setInternal(false).build();
261 builder.addAugmentation(IfTunnel.class, tunnel);
262 LOG.trace("iftunnel {} built from hwvtep {} ",tunnel,node_id);
263 return builder.build();
267 public static InternalTunnel buildInternalTunnel( BigInteger srcDpnId, BigInteger dstDpnId, String trunkInterfaceName) {
268 InternalTunnel tnl = new InternalTunnelBuilder().setKey(new InternalTunnelKey(dstDpnId,srcDpnId)).setDestinationDPN(dstDpnId)
269 .setSourceDPN(srcDpnId)
270 .setTunnelInterfaceName(trunkInterfaceName).build();
274 public static ExternalTunnel buildExternalTunnel(String srcNode, String dstNode, String trunkInterfaceName) {
275 ExternalTunnel extTnl = new ExternalTunnelBuilder().setKey(
276 new ExternalTunnelKey(dstNode, srcNode)).setSourceDevice(srcNode).setDestinationDevice(dstNode).setTunnelInterfaceName(trunkInterfaceName).build();
280 public static List<DPNTEPsInfo> getTunnelMeshInfo(DataBroker dataBroker) {
281 List<DPNTEPsInfo> dpnTEPs= null ;
283 // Read the EndPoint Info from the operational database
284 InstanceIdentifierBuilder<DpnEndpoints> depBuilder = InstanceIdentifier.builder( DpnEndpoints.class) ;
285 InstanceIdentifier<DpnEndpoints> deps = depBuilder.build();
286 Optional<DpnEndpoints> dpnEps = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, deps, dataBroker);
287 if (dpnEps.isPresent()) {
288 DpnEndpoints tn= dpnEps.get() ;
289 dpnTEPs = tn.getDPNTEPsInfo();
290 LOG.debug( "Read from CONFIGURATION datastore - No. of Dpns " , dpnTEPs.size() );
292 LOG.debug( "No Dpn information in CONFIGURATION datastore " );
296 public static int getUniqueId(IdManagerService idManager, String idKey) {
297 AllocateIdInput getIdInput = new AllocateIdInputBuilder()
298 .setPoolName(ITMConstants.ITM_IDPOOL_NAME)
299 .setIdKey(idKey).build();
302 Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
303 RpcResult<AllocateIdOutput> rpcResult = result.get();
304 if(rpcResult.isSuccessful()) {
305 return rpcResult.getResult().getIdValue().intValue();
307 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
309 } catch (InterruptedException | ExecutionException e) {
310 LOG.warn("Exception when getting Unique Id",e);
315 public static void releaseId(IdManagerService idManager, String idKey) {
316 ReleaseIdInput idInput =
317 new ReleaseIdInputBuilder().setPoolName(ITMConstants.ITM_IDPOOL_NAME).setIdKey(idKey).build();
319 Future<RpcResult<Void>> result = idManager.releaseId(idInput);
320 RpcResult<Void> rpcResult = result.get();
321 if(!rpcResult.isSuccessful()) {
322 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
324 } catch (InterruptedException | ExecutionException e) {
325 LOG.warn("Exception when getting Unique Id for key {}", idKey, e);
329 public static List<DPNTEPsInfo> getDPNTEPListFromDPNId(DataBroker dataBroker, List<BigInteger> dpnIds) {
330 List<DPNTEPsInfo> meshedDpnList = getTunnelMeshInfo(dataBroker) ;
331 List<DPNTEPsInfo> cfgDpnList = new ArrayList<DPNTEPsInfo>();
332 if( null != meshedDpnList) {
333 for(BigInteger dpnId : dpnIds) {
334 for( DPNTEPsInfo teps : meshedDpnList ) {
335 if( dpnId.equals(teps.getDPNID()))
336 cfgDpnList.add( teps) ;
343 public static void setUpOrRemoveTerminatingServiceTable(BigInteger dpnId, IMdsalApiManager mdsalManager, boolean addFlag) {
344 String logmsg = ( addFlag == true) ? "Installing" : "Removing";
345 LOG.trace( logmsg + " PUNT to Controller flow in DPN {} ", dpnId );
347 List<ActionInfo> listActionInfo = new ArrayList<ActionInfo>();
348 listActionInfo.add(new ActionInfo(ActionType.punt_to_controller,
352 List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
354 mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {
355 BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID) }));
357 List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>();
358 mkInstructions.add(new InstructionInfo(InstructionType.apply_actions,
361 FlowEntity terminatingServiceTableFlowEntity = MDSALUtil
364 NwConstants.INTERNAL_TUNNEL_TABLE,
365 getFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE,
366 ITMConstants.LLDP_SERVICE_ID), 5, String.format("%s:%d","ITM Flow Entry ",ITMConstants.LLDP_SERVICE_ID),
367 0, 0, ITMConstants.COOKIE_ITM
368 .add(BigInteger.valueOf(ITMConstants.LLDP_SERVICE_ID)),
369 mkMatches, mkInstructions);
371 mdsalManager.installFlow(terminatingServiceTableFlowEntity);
373 mdsalManager.removeFlow(terminatingServiceTableFlowEntity);
374 } catch (Exception e) {
375 LOG.error("Error while setting up Table 36 for {}", dpnId, e);
379 private static String getFlowRef(long termSvcTable, int svcId) {
380 return new StringBuffer().append(termSvcTable).append(svcId).toString();
382 public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier(String schemaName) {
383 return InstanceIdentifier.builder(VtepConfigSchemas.class)
384 .child(VtepConfigSchema.class, new VtepConfigSchemaKey(schemaName)).build();
387 public static InstanceIdentifier<VtepConfigSchema> getVtepConfigSchemaIdentifier() {
388 return InstanceIdentifier.builder(VtepConfigSchemas.class).child(VtepConfigSchema.class).build();
390 public static InstanceIdentifier<VtepConfigSchemas> getVtepConfigSchemasIdentifier() {
391 return InstanceIdentifier.builder(VtepConfigSchemas.class).build();
393 public static InstanceIdentifier<VtepIpPool> getVtepIpPoolIdentifier(String subnetCidr) {
394 return InstanceIdentifier.builder(VtepIpPools.class).child(VtepIpPool.class, new VtepIpPoolKey(subnetCidr))
397 public static VtepConfigSchema validateForAddVtepConfigSchema(VtepConfigSchema schema,
398 List<VtepConfigSchema> existingSchemas) {
399 VtepConfigSchema validSchema = validateVtepConfigSchema(schema);
400 for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
401 if (!StringUtils.equalsIgnoreCase(schema.getSchemaName(), existingSchema.getSchemaName())
402 && schema.getSubnet().equals(existingSchema.getSubnet())) {
403 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
404 Preconditions.checkArgument(false, new StringBuilder("VTEP schema with subnet [").append(subnetCidr)
405 .append("] already exists. Multiple VTEP schemas with same subnet is not allowed.").toString());
408 if (isNotEmpty(getDpnIdList(validSchema.getDpnIds()))) {
409 String tzone = validSchema.getTransportZoneName();
410 List<BigInteger> lstDpns = getConflictingDpnsAlreadyConfiguredWithTz(validSchema.getSchemaName(), tzone,
411 getDpnIdList(validSchema.getDpnIds()), existingSchemas);
412 if (!lstDpns.isEmpty()) {
413 Preconditions.checkArgument(false,
414 new StringBuilder("DPN's ").append(lstDpns).append(" already configured for transport zone ")
415 .append(tzone).append(". Only one end point per transport Zone per Dpn is allowed.")
418 if (schema.getTunnelType().equals(TunnelTypeGre.class)){
419 validateForSingleGreTep(validSchema.getSchemaName(), getDpnIdList(validSchema.getDpnIds()), existingSchemas);
424 private static void validateForSingleGreTep(String schemaName, List<BigInteger> lstDpnsForAdd,
425 List<VtepConfigSchema> existingSchemas) {
426 for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
427 if ((TunnelTypeGre.class).equals(existingSchema.getTunnelType())
428 && !StringUtils.equalsIgnoreCase(schemaName, existingSchema.getSchemaName())) {
429 List<BigInteger> lstConflictingDpns = new ArrayList<>(getDpnIdList(existingSchema.getDpnIds()));
430 lstConflictingDpns.retainAll(emptyIfNull(lstDpnsForAdd));
431 if (!lstConflictingDpns.isEmpty()) {
432 String errMsg = new StringBuilder("DPN's ").append(lstConflictingDpns)
433 .append(" already configured with GRE TEP. Mutiple GRE TEP's on a single DPN are not allowed.")
435 Preconditions.checkArgument(false, errMsg);
440 public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
441 Preconditions.checkNotNull(schema);
442 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
443 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
444 Preconditions.checkArgument((schema.getVlanId() >= 0 && schema.getVlanId() < 4095),
445 "Invalid VLAN ID, range (0-4094)");
446 Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
447 Preconditions.checkNotNull(schema.getSubnet());
448 String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
449 SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
450 IpAddress gatewayIp = schema.getGatewayIp();
451 if (gatewayIp != null) {
452 String strGatewayIp = String.valueOf(gatewayIp.getValue());
453 if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS) && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
454 Preconditions.checkArgument(false, new StringBuilder("Gateway IP address ").append(strGatewayIp)
455 .append(" is not in subnet range ").append(subnetCidr).toString());
458 ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
459 return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
461 public static String validateTunnelType(String tunnelType) {
462 if (tunnelType == null) {
463 tunnelType = ITMConstants.TUNNEL_TYPE_VXLAN;
465 tunnelType = StringUtils.upperCase(tunnelType);
466 String error = new StringBuilder("Invalid tunnel type. Valid values: ")
467 .append(ITMConstants.TUNNEL_TYPE_VXLAN).append(" | ").append(ITMConstants.TUNNEL_TYPE_GRE)
469 Preconditions.checkArgument(ITMConstants.TUNNEL_TYPE_VXLAN.equals(tunnelType)
470 || ITMConstants.TUNNEL_TYPE_GRE.equals(tunnelType), error);
474 private static List<BigInteger> getConflictingDpnsAlreadyConfiguredWithTz(String schemaName, String tzone,
475 List<BigInteger> lstDpns, List<VtepConfigSchema> existingSchemas) {
476 List<BigInteger> lstConflictingDpns = new ArrayList<>();
477 for (VtepConfigSchema schema : emptyIfNull(existingSchemas)) {
478 if (!StringUtils.equalsIgnoreCase(schemaName, schema.getSchemaName())
479 && StringUtils.equals(schema.getTransportZoneName(), tzone)) {
480 lstConflictingDpns = new ArrayList<>(getDpnIdList(schema.getDpnIds()));
481 lstConflictingDpns.retainAll(lstDpns);
482 if (!lstConflictingDpns.isEmpty()) {
487 return lstConflictingDpns;
489 public static VtepConfigSchema constructVtepConfigSchema(String schemaName, String portName, Integer vlanId,
490 String subnetMask, String gatewayIp, String transportZone,String tunnelType, List<BigInteger> dpnIds,
491 String excludeIpFilter) {
492 IpAddress gatewayIpObj = StringUtils.isBlank(gatewayIp) ? null : new IpAddress(gatewayIp.toCharArray());
493 IpPrefix subnet = StringUtils.isBlank(subnetMask) ? null : new IpPrefix(subnetMask.toCharArray());
494 Class<? extends TunnelTypeBase> tunType ;
495 if( tunnelType.equals(ITMConstants.TUNNEL_TYPE_VXLAN))
496 tunType = TunnelTypeVxlan.class ;
498 tunType = TunnelTypeGre.class ;
499 VtepConfigSchemaBuilder schemaBuilder = new VtepConfigSchemaBuilder().setSchemaName(schemaName)
500 .setPortName(portName).setVlanId(vlanId).setSubnet(subnet).setGatewayIp(gatewayIpObj)
501 .setTransportZoneName(transportZone).setTunnelType(tunType).setDpnIds(getDpnIdsListFromBigInt(dpnIds))
502 .setExcludeIpFilter(excludeIpFilter);
503 return schemaBuilder.build();
505 public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
506 final List<IpAddress> lstIpAddress = new ArrayList<>();
507 if (StringUtils.isBlank(excludeIpFilter)) {
510 final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
511 for (String ip : arrIps) {
512 if (StringUtils.countMatches(ip, "-") == 1) {
513 final String[] arrIpRange = StringUtils.split(ip, '-');
514 String strStartIp = StringUtils.trim(arrIpRange[0]);
515 String strEndIp = StringUtils.trim(arrIpRange[1]);
516 Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
517 new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strStartIp)
519 Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
520 new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strEndIp)
522 Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
523 new StringBuilder("Invalid exclude IP filter: IP address [").append(strStartIp)
524 .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
525 Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
526 new StringBuilder("Invalid exclude IP filter: IP address [").append(strEndIp)
527 .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
528 int startIp = subnetInfo.asInteger(strStartIp);
529 int endIp = subnetInfo.asInteger(strEndIp);
531 Preconditions.checkArgument(startIp < endIp,
532 new StringBuilder("Invalid exclude IP filter: Invalid range [").append(ip).append("] ")
534 for (int i = startIp; i <= endIp; i++) {
535 String ipAddress = ipFormat(toIpArray(i));
536 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
539 validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
544 private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
546 String ip = StringUtils.trim(ipAddress);
547 Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
548 new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(ip).toString());
549 Preconditions.checkArgument(subnetInfo.isInRange(ip),
550 new StringBuilder("Invalid exclude IP filter: IP address [").append(ip).append("] not in subnet range ")
551 .append(subnetInfo.getCidrSignature()).toString());
552 lstIpAddress.add(new IpAddress(ip.toCharArray()));
554 private static int[] toIpArray(int val) {
555 int[] ret = new int[4];
556 for (int j = 3; j >= 0; --j) {
557 ret[j] |= ((val >>> 8 * (3 - j)) & (0xff));
561 private static String ipFormat(int[] octets) {
562 StringBuilder str = new StringBuilder();
563 for (int i = 0; i < octets.length; ++i) {
564 str.append(octets[i]);
565 if (i != octets.length - 1) {
569 return str.toString();
571 public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd,
572 List<BigInteger> lstDpnsForDelete, IITMProvider itmProvider) {
573 Preconditions.checkArgument(StringUtils.isNotBlank(schemaName));
574 if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty())
575 && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) {
576 Preconditions.checkArgument(false,
577 new StringBuilder("DPN ID list for add | delete is null or empty in schema ").append(schemaName)
580 VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName);
581 if (schema == null) {
582 Preconditions.checkArgument(false, new StringBuilder("Specified VTEP Schema [").append(schemaName)
583 .append("] doesn't exists!").toString());
585 List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds());
586 if (isNotEmpty(lstDpnsForAdd)) {
587 if (isNotEmpty(existingDpnIds)) {
588 List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds);
589 lstAlreadyExistingDpns.retainAll(lstDpnsForAdd);
590 Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(),
591 new StringBuilder("DPN ID's ").append(lstAlreadyExistingDpns)
592 .append(" already exists in VTEP schema [").append(schemaName).append("]").toString());
594 if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
595 validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd, itmProvider.getAllVtepConfigSchemas());
598 if (isNotEmpty(lstDpnsForDelete)) {
599 if (existingDpnIds == null || existingDpnIds.isEmpty()) {
600 StringBuilder builder = new StringBuilder("DPN ID's ").append(lstDpnsForDelete)
601 .append(" specified for delete from VTEP schema [").append(schemaName)
602 .append("] are not configured in the schema.");
603 Preconditions.checkArgument(false, builder.toString());
604 } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) {
605 List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete);
606 lstConflictingDpns.removeAll(existingDpnIds);
607 StringBuilder builder = new StringBuilder("DPN ID's ").append(lstConflictingDpns)
608 .append(" specified for delete from VTEP schema [").append(schemaName)
609 .append("] are not configured in the schema.");
610 Preconditions.checkArgument(false, builder.toString());
615 public static String getSubnetCidrAsString(IpPrefix subnet) {
616 return (subnet == null) ? StringUtils.EMPTY : String.valueOf(subnet.getValue());
618 public static <T> List<T> emptyIfNull(List<T> list) {
619 return (list == null) ? Collections.<T> emptyList() : list;
621 public static <T> boolean isEmpty(Collection<T> collection) {
622 return (collection == null || collection.isEmpty()) ? true : false;
624 public static <T> boolean isNotEmpty(Collection<T> collection) {
625 return !isEmpty(collection);
627 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) {
628 HwVtep hwVtep = new HwVtep();
629 hwVtep.setGatewayIP(gatewayIP);
630 hwVtep.setHwIp(ipAddress);
631 hwVtep.setIpPrefix(ipPrefix);
632 hwVtep.setNode_id(node_id);
633 hwVtep.setTopo_id(topo_id);
634 hwVtep.setTransportZone(transportZone.getZoneName());
635 hwVtep.setTunnel_type(tunnel_type);
636 hwVtep.setVlanID(vlanID);
640 public static String getHwParentIf(String topo_id, String srcNodeid) {
641 return String.format("%s:%s", topo_id, srcNodeid);
644 public static <T extends DataObject> void syncWrite(LogicalDatastoreType datastoreType,
645 InstanceIdentifier<T> path, T data, DataBroker broker) {
646 WriteTransaction tx = broker.newWriteOnlyTransaction();
647 tx.put(datastoreType, path, data, true);
648 CheckedFuture<Void, TransactionCommitFailedException> futures = tx.submit();
651 } catch (InterruptedException | ExecutionException e) {
652 LOG.error("ITMUtils:SyncWrite , Error writing to datastore (path, data) : ({}, {})", path, data);
653 throw new RuntimeException(e.getMessage());
657 public static List<BigInteger> getDpnIdList( List<DpnIds> dpnIds ) {
658 List<BigInteger> dpnList = new ArrayList<BigInteger>() ;
659 for( DpnIds dpn : dpnIds) {
660 dpnList.add(dpn.getDPN()) ;
665 public static List<DpnIds> getDpnIdsListFromBigInt( List<BigInteger> dpnIds) {
666 List<DpnIds> dpnIdList = new ArrayList<DpnIds>() ;
667 DpnIdsBuilder builder = new DpnIdsBuilder() ;
668 for( BigInteger dpnId : dpnIds) {
669 dpnIdList.add(builder.setKey(new DpnIdsKey(dpnId)).setDPN(dpnId).build() );