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.netvirt.neutronvpn;
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.SettableFuture;
13 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
14 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
15 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
16 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
17 import org.opendaylight.genius.mdsalutil.MDSALUtil;
18 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
19 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInstances;
20 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInterfaces;
21 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.VpnTargets;
22 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.VpnTargetsBuilder;
23 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.vpntargets.VpnTarget;
24 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.vpntargets
26 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.vpntargets.VpnTargetKey;
27 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstance;
28 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceBuilder;
29 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceKey;
30 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.vpn.instance
32 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterface;
33 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterfaceBuilder;
34 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterfaceKey;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.LockManagerService;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.Adjacencies;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.AdjacenciesBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.adjacency.list.Adjacency;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.adjacency.list.AdjacencyBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.RouterInterfacesMap;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.router.interfaces.map.RouterInterfaces;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.router.interfaces.map.RouterInterfacesBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.router.interfaces.map.RouterInterfacesKey;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.router.interfaces.map.router.interfaces.Interfaces;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.router.interfaces.map.router.interfaces.InterfacesBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.router.interfaces.map.router.interfaces.InterfacesKey;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.adjacency.list.AdjacencyKey;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.l3.attributes.Routes;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.SubnetKey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.*;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.createl3vpn.input.L3vpn;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.getl3vpn.output.L3vpnInstances;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.getl3vpn.output
67 .L3vpnInstancesBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapKey;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpnmaps.VpnMap;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpnmaps.VpnMapBuilder;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpnmaps.VpnMapKey;
74 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
75 import org.opendaylight.yangtools.yang.common.RpcError;
76 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
77 import org.opendaylight.yangtools.yang.common.RpcResult;
78 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
80 import java.util.EventListener;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
85 import java.util.ArrayList;
86 import java.util.Arrays;
87 import java.util.List;
88 import java.util.concurrent.ExecutionException;
89 import java.util.concurrent.Future;
91 public class NeutronvpnManager implements NeutronvpnService, AutoCloseable , EventListener{
93 private static final Logger logger = LoggerFactory.getLogger(NeutronvpnManager.class);
94 private final DataBroker broker;
95 private LockManagerService lockManager;
96 IMdsalApiManager mdsalUtil;
97 private NotificationPublishService notificationPublishService;
98 private NotificationService notificationService;
99 Boolean isExternalVpn;
102 * @param db - dataBroker reference
103 * @param mdsalManager - MDSAL Util API access
105 public NeutronvpnManager(final DataBroker db, IMdsalApiManager mdsalManager,NotificationPublishService notiPublishService,
106 NotificationService notiService) {
108 mdsalUtil = mdsalManager;
109 notificationPublishService = notiPublishService;
110 notificationService = notiService;
113 public void setLockManager(LockManagerService lockManager) {
114 this.lockManager = lockManager;
118 public void close() throws Exception {
119 logger.info("Neutron VPN Manager Closed");
122 protected Subnetmap updateSubnetNode(Uuid subnetId, String subnetIp, Uuid tenantId, Uuid networkId, Uuid routerId,
123 Uuid vpnId, Uuid portId) {
124 Subnetmap subnetmap = null;
125 SubnetmapBuilder builder = null;
126 boolean isLockAcquired = false;
127 InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class).
128 child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
130 Optional<Subnetmap> sn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, id);
131 logger.debug("updating Subnet :read: ");
132 if (sn.isPresent()) {
133 builder = new SubnetmapBuilder(sn.get());
134 logger.debug("updating Subnet :existing: ");
136 builder = new SubnetmapBuilder().setKey(new SubnetmapKey(subnetId)).setId(subnetId);
137 logger.debug("updating Subnet :new: ");
140 if (subnetIp != null) {
141 builder.setSubnetIp(subnetIp);
143 if (routerId != null) {
144 builder.setRouterId(routerId);
146 if (networkId != null) {
147 builder.setNetworkId(networkId);
150 builder.setVpnId(vpnId);
152 if (tenantId != null) {
153 builder.setTenantId(tenantId);
156 if (portId != null) {
157 List<Uuid> portList = builder.getPortList();
158 if (portList == null) {
159 portList = new ArrayList<Uuid>();
161 portList.add(portId);
162 builder.setPortList(portList);
165 subnetmap = builder.build();
166 isLockAcquired = NeutronvpnUtils.lock(lockManager, subnetId.getValue());
167 logger.debug("Creating/Updating subnetMap node: {} ", subnetId.getValue());
168 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, subnetmap);
169 } catch (Exception e) {
170 logger.error("Updation of subnetMap failed for node: {}", subnetId.getValue());
172 if (isLockAcquired) {
173 NeutronvpnUtils.unlock(lockManager, subnetId.getValue());
179 protected Subnetmap removeFromSubnetNode(Uuid subnetId, Uuid networkId, Uuid routerId, Uuid vpnId, Uuid portId) {
180 Subnetmap subnetmap = null;
181 boolean isLockAcquired = false;
182 InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class).
183 child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
185 Optional<Subnetmap> sn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, id);
186 if (sn.isPresent()) {
187 SubnetmapBuilder builder = new SubnetmapBuilder(sn.get());
188 if (routerId != null) {
189 builder.setRouterId(null);
191 if (networkId != null) {
192 builder.setNetworkId(null);
195 builder.setVpnId(null);
197 if (portId != null && builder.getPortList() != null) {
198 List<Uuid> portList = builder.getPortList();
199 portList.remove(portId);
200 builder.setPortList(portList);
203 subnetmap = builder.build();
204 isLockAcquired = NeutronvpnUtils.lock(lockManager, subnetId.getValue());
205 logger.debug("Removing from existing subnetmap node: {} ", subnetId.getValue());
206 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, subnetmap);
208 logger.warn("removing from non-existing subnetmap node: {} ", subnetId.getValue());
210 } catch (Exception e) {
211 logger.error("Removal from subnetmap failed for node: {}", subnetId.getValue());
213 if (isLockAcquired) {
214 NeutronvpnUtils.unlock(lockManager, subnetId.getValue());
220 protected void deleteSubnetMapNode(Uuid subnetId) {
221 boolean isLockAcquired = false;
222 InstanceIdentifier<Subnetmap> subnetMapIdentifier = InstanceIdentifier.builder(Subnetmaps.class)
223 .child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
224 logger.debug("removing subnetMap node: {} ", subnetId.getValue());
226 isLockAcquired = NeutronvpnUtils.lock(lockManager, subnetId.getValue());
227 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, subnetMapIdentifier);
228 } catch (Exception e) {
229 logger.error("Delete subnetMap node failed for subnet : {} ", subnetId.getValue());
231 if (isLockAcquired) {
232 NeutronvpnUtils.unlock(lockManager, subnetId.getValue());
237 private void updateVpnInstanceNode(String vpnName, List<String> rd, List<String> irt, List<String> ert) {
239 VpnInstanceBuilder builder = null;
240 List<VpnTarget> vpnTargetList = new ArrayList<VpnTarget>();
241 boolean isLockAcquired = false;
242 InstanceIdentifier<VpnInstance> vpnIdentifier = InstanceIdentifier.builder(VpnInstances.class).
243 child(VpnInstance.class, new VpnInstanceKey(vpnName)).build();
245 Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
247 logger.debug("Creating/Updating a new vpn-instance node: {} ", vpnName);
248 if (optionalVpn.isPresent()) {
249 builder = new VpnInstanceBuilder(optionalVpn.get());
250 logger.debug("updating existing vpninstance node");
252 builder = new VpnInstanceBuilder().setKey(new VpnInstanceKey(vpnName)).setVpnInstanceName(vpnName);
254 if (irt != null && !irt.isEmpty()) {
255 if (ert != null && !ert.isEmpty()) {
256 List<String> commonRT = new ArrayList<String>(irt);
257 commonRT.retainAll(ert);
259 for (String common : commonRT) {
262 VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(common)).setVrfRTValue
263 (common).setVrfRTType(VpnTarget.VrfRTType.Both).build();
264 vpnTargetList.add(vpnTarget);
267 for (String importRT : irt) {
268 VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(importRT)).setVrfRTValue
269 (importRT).setVrfRTType(VpnTarget.VrfRTType.ImportExtcommunity).build();
270 vpnTargetList.add(vpnTarget);
274 if (ert != null && !ert.isEmpty()) {
275 for (String exportRT : ert) {
276 VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(exportRT)).setVrfRTValue
277 (exportRT).setVrfRTType(VpnTarget.VrfRTType.ExportExtcommunity).build();
278 vpnTargetList.add(vpnTarget);
282 VpnTargets vpnTargets = new VpnTargetsBuilder().setVpnTarget(vpnTargetList).build();
284 Ipv4FamilyBuilder ipv4vpnBuilder = new Ipv4FamilyBuilder().setVpnTargets(vpnTargets);
286 if (rd != null && !rd.isEmpty()) {
287 ipv4vpnBuilder.setRouteDistinguisher(rd.get(0));
290 VpnInstance newVpn = builder.setIpv4Family(ipv4vpnBuilder.build()).build();
291 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnName);
292 logger.debug("Creating/Updating vpn-instance for {} ", vpnName);
293 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnIdentifier, newVpn);
294 } catch (Exception e) {
295 logger.error("Update VPN Instance node failed for node: {} {} {} {}", vpnName, rd, irt, ert);
297 if (isLockAcquired) {
298 NeutronvpnUtils.unlock(lockManager, vpnName);
303 private void deleteVpnMapsNode(Uuid vpnid) {
304 boolean isLockAcquired = false;
305 InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
306 .child(VpnMap.class, new VpnMapKey(vpnid)).build();
307 logger.debug("removing vpnMaps node: {} ", vpnid.getValue());
309 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnid.getValue());
310 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
311 } catch (Exception e) {
312 logger.error("Delete vpnMaps node failed for vpn : {} ", vpnid.getValue());
314 if (isLockAcquired) {
315 NeutronvpnUtils.unlock(lockManager, vpnid.getValue());
320 private void updateVpnMaps(Uuid vpnId, String name, Uuid router, Uuid tenantId, List<Uuid> networks) {
321 VpnMapBuilder builder;
322 boolean isLockAcquired = false;
323 InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
324 .child(VpnMap.class, new VpnMapKey(vpnId)).build();
326 Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
328 if (optionalVpnMap.isPresent()) {
329 builder = new VpnMapBuilder(optionalVpnMap.get());
331 builder = new VpnMapBuilder().setKey(new VpnMapKey(vpnId)).setVpnId(vpnId);
335 builder.setName(name);
337 if (tenantId != null) {
338 builder.setTenantId(tenantId);
340 if (router != null) {
341 builder.setRouterId(router);
343 if (networks != null) {
344 List<Uuid> nwList = builder.getNetworkIds();
345 if (nwList == null) {
346 nwList = new ArrayList<Uuid>();
348 nwList.addAll(networks);
349 builder.setNetworkIds(nwList);
352 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
353 logger.debug("Creating/Updating vpnMaps node: {} ", vpnId.getValue());
354 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier, builder.build());
355 logger.debug("VPNMaps DS updated for VPN {} ", vpnId.getValue());
356 } catch (Exception e) {
357 logger.error("UpdateVpnMaps failed for node: {} ", vpnId.getValue());
359 if (isLockAcquired) {
360 NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
365 private void clearFromVpnMaps(Uuid vpnId, Uuid routerId, List<Uuid> networkIds) {
366 boolean isLockAcquired = false;
367 InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
368 .child(VpnMap.class, new VpnMapKey(vpnId)).build();
369 Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
371 if (optionalVpnMap.isPresent()) {
372 VpnMap vpnMap = optionalVpnMap.get();
373 VpnMapBuilder vpnMapBuilder = new VpnMapBuilder(vpnMap);
374 if (routerId != null) {
375 if (vpnMap.getNetworkIds() == null && routerId.equals(vpnMap.getVpnId())) {
377 // remove entire node in case of internal VPN
378 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
379 logger.debug("removing vpnMaps node: {} ", vpnId);
380 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
381 } catch (Exception e) {
382 logger.error("Deletion of vpnMaps node failed for vpn {}", vpnId.getValue());
384 if (isLockAcquired) {
385 NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
390 vpnMapBuilder.setRouterId(null);
392 if (networkIds != null) {
393 List<Uuid> vpnNw = vpnMap.getNetworkIds();
394 for (Uuid nw : networkIds) {
397 if (vpnNw.isEmpty()) {
398 logger.debug("setting networks null in vpnMaps node: {} ", vpnId.getValue());
399 vpnMapBuilder.setNetworkIds(null);
401 vpnMapBuilder.setNetworkIds(vpnNw);
406 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
407 logger.debug("clearing from vpnMaps node: {} ", vpnId.getValue());
408 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier, vpnMapBuilder.build
410 } catch (Exception e) {
411 logger.error("Clearing from vpnMaps node failed for vpn {}", vpnId.getValue());
413 if (isLockAcquired) {
414 NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
418 logger.error("VPN : {} not found", vpnId.getValue());
420 logger.debug("Clear from VPNMaps DS successful for VPN {} ", vpnId.getValue());
423 private void deleteVpnInstance(Uuid vpnId) {
424 boolean isLockAcquired = false;
425 InstanceIdentifier<VpnInstance> vpnIdentifier = InstanceIdentifier.builder(VpnInstances.class).
426 child(VpnInstance.class, new VpnInstanceKey(vpnId.getValue())).build();
428 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
429 logger.debug("Deleting vpnInstance {}", vpnId.getValue());
430 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnIdentifier);
431 } catch (Exception e) {
432 logger.error("Deletion of VPNInstance node failed for VPN {}", vpnId.getValue());
434 if (isLockAcquired) {
435 NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
440 protected void createVpnInterface(Uuid vpnId, Port port) {
441 boolean isLockAcquired = false;
442 if (vpnId == null || port == null) {
445 String infName = port.getUuid().getValue();
446 List<Adjacency> adjList = new ArrayList<Adjacency>();
447 InstanceIdentifier<VpnInterface> vpnIfIdentifier = NeutronvpnUtils.buildVpnInterfaceIdentifier(infName);
449 // find router associated to vpn
450 Uuid routerId = NeutronvpnUtils.getRouterforVpn(broker, vpnId);
452 if (routerId != null) {
453 rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
455 // find all subnets to which this port is associated
456 List<FixedIps> ips = port.getFixedIps();
457 // create adjacency list
458 for (FixedIps ip : ips) {
459 // create vm adjacency
460 StringBuilder IpPrefixBuild = new StringBuilder(ip.getIpAddress().getIpv4Address().getValue());
461 String IpPrefix = IpPrefixBuild.append("/32").toString();
462 Adjacency vmAdj = new AdjacencyBuilder().setKey(new AdjacencyKey(IpPrefix)).setIpAddress(IpPrefix)
463 .setMacAddress(port.getMacAddress()).build();
465 // create extra route adjacency
466 if (rtr != null && rtr.getRoutes() != null) {
467 List<Routes> routeList = rtr.getRoutes();
468 List<Adjacency> erAdjList = addAdjacencyforExtraRoute(routeList, false, infName);
469 if (erAdjList != null && !erAdjList.isEmpty()) {
470 adjList.addAll(erAdjList);
474 // create vpn-interface on this neutron port
475 Adjacencies adjs = new AdjacenciesBuilder().setAdjacency(adjList).build();
476 VpnInterfaceBuilder vpnb = new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(infName)).
477 setName(infName).setVpnInstanceName(vpnId.getValue()).addAugmentation(Adjacencies.class, adjs);
478 VpnInterface vpnIf = vpnb.build();
481 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
482 logger.debug("Creating vpn interface {}", vpnIf);
483 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier, vpnIf);
484 } catch (Exception ex) {
485 logger.error("Creation of vpninterface {} failed due to {}", infName, ex);
487 if (isLockAcquired) {
488 NeutronvpnUtils.unlock(lockManager, infName);
493 protected void deleteVpnInterface(Port port) {
496 boolean isLockAcquired = false;
497 String infName = port.getUuid().getValue();
498 InstanceIdentifier<VpnInterface> vpnIfIdentifier = NeutronvpnUtils.buildVpnInterfaceIdentifier(infName);
501 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
502 logger.debug("Deleting vpn interface {}", infName);
503 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier);
504 } catch (Exception ex) {
505 logger.error("Deletion of vpninterface {} failed due to {}", infName, ex);
507 if (isLockAcquired) {
508 NeutronvpnUtils.unlock(lockManager, infName);
514 protected void updateVpnInterface(Uuid vpnId, Port port) {
515 if (vpnId == null || port == null) {
518 boolean isLockAcquired = false;
519 String infName = port.getUuid().getValue();
520 InstanceIdentifier<VpnInterface> vpnIfIdentifier = NeutronvpnUtils.buildVpnInterfaceIdentifier(infName);
522 Optional<VpnInterface> optionalVpnInterface = NeutronvpnUtils.read(broker, LogicalDatastoreType
523 .CONFIGURATION, vpnIfIdentifier);
524 if (optionalVpnInterface.isPresent()) {
525 VpnInterfaceBuilder vpnIfBuilder = new VpnInterfaceBuilder(optionalVpnInterface.get());
526 VpnInterface vpnIf = vpnIfBuilder.setVpnInstanceName(vpnId.getValue()).build();
527 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
528 logger.debug("Updating vpn interface {}", vpnIf);
529 MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier, vpnIf);
531 logger.error("VPN Interface {} not found", infName);
533 } catch (Exception ex) {
534 logger.error("Updation of vpninterface {} failed due to {}", infName, ex);
536 if (isLockAcquired) {
537 NeutronvpnUtils.unlock(lockManager, infName);
542 public void createL3Vpn(Uuid vpn, String name, Uuid tenant, List<String> rd, List<String> irt, List<String> ert,
543 Uuid router, List<Uuid> networks) {
545 // Update VPN Instance node
546 updateVpnInstanceNode(vpn.getValue(), rd, irt, ert);
548 // Update local vpn-subnet DS
549 updateVpnMaps(vpn, name, router, tenant, networks);
551 if (router != null) {
552 associateRouterToVpn(vpn, router);
554 if (networks != null) {
555 associateNetworksToVpn(vpn, networks);
560 public Future<RpcResult<CreateL3VPNOutput>> createL3VPN(CreateL3VPNInput input) {
562 CreateL3VPNOutputBuilder opBuilder = new CreateL3VPNOutputBuilder();
563 SettableFuture<RpcResult<CreateL3VPNOutput>> result = SettableFuture.create();
564 List<RpcError> errorList = new ArrayList<RpcError>();
565 int failurecount = 0;
566 int warningcount = 0;
568 List<L3vpn> vpns = input.getL3vpn();
569 for (L3vpn vpn : vpns) {
570 RpcError error = null;
572 if (vpn.getRouteDistinguisher() == null || vpn.getImportRT() == null || vpn.getExportRT() == null) {
573 msg = String.format("Creation of L3VPN failed for VPN %s due to absence of RD/iRT/eRT input",
574 vpn.getId().getValue());
576 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
577 errorList.add(error);
581 if (vpn.getRouteDistinguisher().size() > 1) {
582 msg = String.format("Creation of L3VPN failed for VPN %s due to multiple RD input %s",
583 vpn.getId().getValue(), vpn.getRouteDistinguisher());
585 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
586 errorList.add(error);
590 if (vpn.getRouterId() != null) {
591 if (NeutronvpnUtils.getNeutronRouter(broker, vpn.getRouterId()) == null) {
592 msg = String.format("Creation of L3VPN failed for VPN %s due to router not found %s",
593 vpn.getId().getValue(), vpn.getRouterId().getValue());
595 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
596 errorList.add(error);
600 Uuid vpnId = NeutronvpnUtils.getVpnForRouter(broker, vpn.getRouterId(), true);
602 msg = String.format("Creation of L3VPN failed for VPN %s due to router %s already associated to " +
603 "another VPN %s", vpn.getId().getValue(), vpn.getRouterId().getValue(), vpnId.getValue());
605 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
606 errorList.add(error);
611 if (vpn.getNetworkIds() != null) {
612 for (Uuid nw : vpn.getNetworkIds()) {
613 Network network = NeutronvpnUtils.getNeutronNetwork(broker, nw);
614 Uuid vpnId = NeutronvpnUtils.getVpnForNetwork(broker, nw);
615 if (network == null) {
616 msg = String.format("Creation of L3VPN failed for VPN %s due to network not found %s",
617 vpn.getId().getValue(), nw.getValue());
619 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
620 errorList.add(error);
622 } else if (vpnId != null) {
623 msg = String.format("Creation of L3VPN failed for VPN %s due to network %s already associated" +
624 " to another VPN %s", vpn.getId().getValue(), nw.getValue(), vpnId.getValue());
626 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
627 errorList.add(error);
636 createL3Vpn(vpn.getId(), vpn.getName(), vpn.getTenantId(), vpn.getRouteDistinguisher(),
637 vpn.getImportRT(), vpn.getExportRT(), vpn.getRouterId(), vpn.getNetworkIds());
638 } catch (Exception ex) {
639 msg = String.format("Creation of L3VPN failed for VPN %s", vpn.getId().getValue());
640 logger.error(msg, ex);
641 error = RpcResultBuilder.newError(ErrorType.APPLICATION, msg, ex.getMessage());
642 errorList.add(error);
646 // if at least one succeeds; result is success
647 // if none succeeds; result is failure
648 if (failurecount + warningcount == vpns.size()) {
649 result.set(RpcResultBuilder.<CreateL3VPNOutput>failed().withRpcErrors(errorList).build());
651 List<String> errorResponseList = new ArrayList<>();
652 if (!errorList.isEmpty()) {
653 for (RpcError rpcError : errorList) {
654 String errorResponse = String.format("ErrorType: " + rpcError.getErrorType() + ", " + "ErrorTag: " +
655 rpcError.getTag() + ", " + "ErrorMessage: " + rpcError.getMessage());
656 errorResponseList.add(errorResponse);
659 errorResponseList.add("Operation successful with no errors");
661 opBuilder.setResponse(errorResponseList);
662 result.set(RpcResultBuilder.<CreateL3VPNOutput>success().withResult(opBuilder.build()).build());
668 public Future<RpcResult<GetL3VPNOutput>> getL3VPN(GetL3VPNInput input) {
670 GetL3VPNOutputBuilder opBuilder = new GetL3VPNOutputBuilder();
671 SettableFuture<RpcResult<GetL3VPNOutput>> result = SettableFuture.create();
672 Uuid inputVpnId = input.getId();
673 List<VpnInstance> vpns = new ArrayList<VpnInstance>();
676 if (inputVpnId == null) {
678 InstanceIdentifier<VpnInstances> vpnsIdentifier =
679 InstanceIdentifier.builder(VpnInstances.class).build();
680 Optional<VpnInstances> optionalVpns = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
682 if (optionalVpns.isPresent() && optionalVpns.get().getVpnInstance() != null) {
683 for (VpnInstance vpn : optionalVpns.get().getVpnInstance()) {
684 // eliminating internal VPNs from getL3VPN output
685 if (vpn.getIpv4Family().getRouteDistinguisher() != null) {
691 result.set(RpcResultBuilder.<GetL3VPNOutput>failed()
692 .withWarning(ErrorType.PROTOCOL, "", "No VPN is present").build());
696 String name = inputVpnId.getValue();
697 InstanceIdentifier<VpnInstance> vpnIdentifier =
698 InstanceIdentifier.builder(VpnInstances.class)
699 .child(VpnInstance.class, new VpnInstanceKey(name)).build();
700 // read VpnInstance Info
701 Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
703 if (optionalVpn.isPresent()) {
704 vpns.add(optionalVpn.get());
706 String message = String.format("GetL3VPN failed because VPN %s is not present", name);
707 logger.error(message);
708 result.set(RpcResultBuilder.<GetL3VPNOutput>failed()
709 .withWarning(ErrorType.PROTOCOL, "invalid-value", message).build());
712 List<L3vpnInstances> l3vpnList = new ArrayList<L3vpnInstances>();
713 for (VpnInstance vpnInstance : vpns) {
714 Uuid vpnId = new Uuid(vpnInstance.getVpnInstanceName());
716 InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class).child(VpnMap
717 .class, new VpnMapKey(vpnId)).build();
718 L3vpnInstancesBuilder l3vpn = new L3vpnInstancesBuilder();
720 List<String> rd = Arrays.asList(vpnInstance.getIpv4Family().getRouteDistinguisher().split(","));
721 List<VpnTarget> vpnTargetList = vpnInstance.getIpv4Family().getVpnTargets().getVpnTarget();
723 List<String> ertList = new ArrayList<String>();
724 List<String> irtList = new ArrayList<String>();
726 for (VpnTarget vpnTarget : vpnTargetList) {
727 if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.ExportExtcommunity) {
728 ertList.add(vpnTarget.getVrfRTValue());
730 if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.ImportExtcommunity) {
731 irtList.add(vpnTarget.getVrfRTValue());
733 if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.Both) {
734 ertList.add(vpnTarget.getVrfRTValue());
735 irtList.add(vpnTarget.getVrfRTValue());
739 l3vpn.setId(vpnId).setRouteDistinguisher(rd).setImportRT(irtList).setExportRT(ertList);
740 Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
742 if (optionalVpnMap.isPresent()) {
743 VpnMap vpnMap = optionalVpnMap.get();
744 l3vpn.setRouterId(vpnMap.getRouterId()).setNetworkIds(vpnMap.getNetworkIds())
745 .setTenantId(vpnMap.getTenantId()).setName(vpnMap.getName());
747 l3vpnList.add(l3vpn.build());
750 opBuilder.setL3vpnInstances(l3vpnList);
751 result.set(RpcResultBuilder.<GetL3VPNOutput>success().withResult(opBuilder.build()).build());
753 } catch (Exception ex) {
754 String message = String.format("GetL3VPN failed due to %s", ex.getMessage());
755 logger.error(message, ex);
756 result.set(RpcResultBuilder.<GetL3VPNOutput>failed().withError(ErrorType.APPLICATION, message).build());
762 public Future<RpcResult<DeleteL3VPNOutput>> deleteL3VPN(DeleteL3VPNInput input) {
764 DeleteL3VPNOutputBuilder opBuilder = new DeleteL3VPNOutputBuilder();
765 SettableFuture<RpcResult<DeleteL3VPNOutput>> result = SettableFuture.create();
766 List<RpcError> errorList = new ArrayList<RpcError>();
768 int failurecount = 0;
769 int warningcount = 0;
770 List<Uuid> vpns = input.getId();
771 for (Uuid vpn : vpns) {
775 InstanceIdentifier<VpnInstance> vpnIdentifier =
776 InstanceIdentifier.builder(VpnInstances.class)
777 .child(VpnInstance.class, new VpnInstanceKey(vpn.getValue())).build();
778 Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
780 if (optionalVpn.isPresent()) {
783 msg = String.format("VPN with vpnid: %s does not exist", vpn.getValue());
785 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-value", msg);
786 errorList.add(error);
789 } catch (Exception ex) {
790 msg = String.format("Deletion of L3VPN failed when deleting for uuid %s", vpn.getValue());
791 logger.error(msg, ex);
792 error = RpcResultBuilder.newError(ErrorType.APPLICATION, msg, ex.getMessage());
793 errorList.add(error);
797 // if at least one succeeds; result is success
798 // if none succeeds; result is failure
799 if (failurecount + warningcount == vpns.size()) {
800 result.set(RpcResultBuilder.<DeleteL3VPNOutput>failed().withRpcErrors(errorList).build());
802 List<String> errorResponseList = new ArrayList<>();
803 if (!errorList.isEmpty()) {
804 for (RpcError rpcError : errorList) {
805 String errorResponse = String.format("ErrorType: " + rpcError.getErrorType() + ", " + "ErrorTag: " +
806 rpcError.getTag() + ", " + "ErrorMessage: " + rpcError.getMessage());
807 errorResponseList.add(errorResponse);
810 errorResponseList.add("Operation successful with no errors");
812 opBuilder.setResponse(errorResponseList);
813 result.set(RpcResultBuilder.<DeleteL3VPNOutput>success().withResult(opBuilder.build()).build());
818 protected void addSubnetToVpn(Uuid vpnId, Uuid subnet) {
819 logger.debug("Adding subnet {} to vpn {}", subnet.getValue(), vpnId.getValue());
820 Subnetmap sn = updateSubnetNode(subnet, null, null, null, null, vpnId, null);
821 boolean isLockAcquired = false;
822 String lockName = vpnId.getValue() + subnet.getValue();
823 String elanInstanceName = sn.getNetworkId().getValue();
824 InstanceIdentifier<ElanInstance>elanIdentifierId = InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
825 Optional<ElanInstance> elanInstance = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId);
826 long elanTag = elanInstance.get().getElanTag();
827 Uuid routerId = NeutronvpnUtils.getVpnMap(broker, vpnId).getRouterId();
828 if (vpnId.equals(routerId)) {
829 isExternalVpn = false;
831 isExternalVpn = true;
834 isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
835 checkAndPublishSubnetAddNotification(subnet, sn.getSubnetIp(), vpnId.getValue(), isExternalVpn, elanTag);
836 logger.debug("Subnet added to Vpn notification sent");
837 }catch (Exception e){
838 logger.error("Subnet added to Vpn notification failed",e);
840 if (isLockAcquired) {
841 NeutronvpnUtils.unlock(lockManager, lockName);
844 // Check if there are ports on this subnet and add corresponding vpn-interfaces
845 List<Uuid> portList = sn.getPortList();
846 if (portList != null) {
847 for (Uuid port : sn.getPortList()) {
848 logger.debug("adding vpn-interface for port {}", port.getValue());
849 createVpnInterface(vpnId, NeutronvpnUtils.getNeutronPort(broker, port));
854 protected void updateVpnForSubnet(Uuid vpnId, Uuid subnet, boolean isBeingAssociated) {
855 logger.debug("Updating VPN {} for subnet {}", vpnId.getValue(), subnet.getValue());
856 Subnetmap sn = updateSubnetNode(subnet, null, null, null, null, vpnId, null);
857 boolean isLockAcquired = false;
858 String lockName = vpnId.getValue() + subnet.getValue();
859 String elanInstanceName = sn.getNetworkId().getValue();
860 InstanceIdentifier<ElanInstance>elanIdentifierId = InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
861 Optional<ElanInstance> elanInstance = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId);
862 long elanTag = elanInstance.get().getElanTag();
864 isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
865 checkAndPublishSubnetUpdNotification(subnet, sn.getSubnetIp(), vpnId.getValue(), isBeingAssociated, elanTag);
866 logger.debug("Subnet updated in Vpn notification sent");
867 }catch (Exception e){
868 logger.error("Subnet updated in Vpn notification failed",e);
870 if (isLockAcquired) {
871 NeutronvpnUtils.unlock(lockManager, lockName);
874 // Check for ports on this subnet and update association of corresponding vpn-interfaces to external vpn
875 List<Uuid> portList = sn.getPortList();
876 if (portList != null) {
877 for (Uuid port : sn.getPortList()) {
878 logger.debug("Updating vpn-interface for port {}", port.getValue());
879 updateVpnInterface(vpnId, NeutronvpnUtils.getNeutronPort(broker, port));
886 // router-interfaces-map
887 // list router-interfaces {
889 // leaf router-id { type yang:uuid; }
892 // leaf interface-id { type yang:uuid; }
896 InstanceIdentifier<RouterInterfaces> getRouterInterfacesId(Uuid routerId) {
897 return InstanceIdentifier.builder(RouterInterfacesMap.class)
898 .child(RouterInterfaces.class, new RouterInterfacesKey(routerId)).build();
900 void addToNeutronRouterInterfacesMap(Uuid routerId, String interfaceName) {
901 InstanceIdentifier<RouterInterfaces> routerInterfacesId = getRouterInterfacesId(routerId);
902 Optional<RouterInterfaces> optRouterInterfaces = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId);
903 Interfaces routerInterface = new InterfacesBuilder().setKey(new InterfacesKey(interfaceName)).setInterfaceId(interfaceName).build();
904 if(optRouterInterfaces.isPresent()) {
905 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId.child(Interfaces.class, new InterfacesKey(interfaceName)), routerInterface);
907 RouterInterfacesBuilder builder = new RouterInterfacesBuilder().setRouterId(routerId);
908 List<Interfaces> interfaces = new ArrayList<>();
909 interfaces.add(routerInterface);
910 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId, builder.setInterfaces(interfaces).build());
914 void removeFromNeutronRouterInterfacesMap(Uuid routerId, String interfaceName) {
915 InstanceIdentifier<RouterInterfaces> routerInterfacesId = getRouterInterfacesId(routerId);
916 Optional<RouterInterfaces> optRouterInterfaces = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId);
917 Interfaces routerInterface = new InterfacesBuilder().setKey(new InterfacesKey(interfaceName)).setInterfaceId(interfaceName).build();
918 if(optRouterInterfaces.isPresent()) {
919 RouterInterfaces routerInterfaces = optRouterInterfaces.get();
920 List<Interfaces> interfaces = routerInterfaces.getInterfaces();
921 if(interfaces != null && interfaces.remove(routerInterface)) {
922 if(interfaces.isEmpty()) {
923 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId);
925 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId.child(Interfaces.class, new InterfacesKey(interfaceName)));
931 protected List<Adjacency> addAdjacencyforExtraRoute(List<Routes> routeList, boolean rtrUp, String vpnifname) {
932 List<Adjacency> adjList = new ArrayList<Adjacency>();
933 for (Routes route : routeList) {
934 if (route != null && route.getNexthop() != null && route.getDestination() != null) {
935 boolean isLockAcquired = false;
936 String nextHop = String.valueOf(route.getNexthop().getValue());
937 String destination = String.valueOf(route.getDestination().getValue());
939 String infName = NeutronvpnUtils.getNeutronPortNamefromPortFixedIp(broker, nextHop);
940 logger.trace("Adding extra route with nexthop {}, destination {}, infName {}", nextHop,
941 destination, infName);
942 Adjacency erAdj = new AdjacencyBuilder().setIpAddress(destination).setNextHopIp(nextHop).setKey
943 (new AdjacencyKey(destination)).build();
944 if (rtrUp == false) {
945 if (infName.equals(vpnifname)) {
950 InstanceIdentifier<VpnInterface> vpnIfIdentifier = InstanceIdentifier.builder(VpnInterfaces.class).
951 child(VpnInterface.class, new VpnInterfaceKey(infName)).build();
953 Optional<VpnInterface> optionalVpnInterface = NeutronvpnUtils.read(broker, LogicalDatastoreType
954 .CONFIGURATION, vpnIfIdentifier);
955 if (optionalVpnInterface.isPresent()) {
956 Adjacencies erAdjs = new AdjacenciesBuilder().setAdjacency(Arrays.asList(erAdj)).build();
957 VpnInterface vpnIf = new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(infName))
958 .addAugmentation(Adjacencies.class, erAdjs).build();
959 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
960 logger.debug("Adding extra route {}", route);
961 MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier, vpnIf);
963 logger.error("VM adjacency for interface {} not present ; cannot add extra route adjacency",
966 } catch (Exception e) {
967 logger.error("exception in adding extra route: {}" + e);
969 if (isLockAcquired) {
970 NeutronvpnUtils.unlock(lockManager, infName);
974 logger.error("Incorrect input received for extra route. {}", route);
980 protected void removeAdjacencyforExtraRoute(List<Routes> routeList) {
981 for (Routes route : routeList) {
982 if (route != null && route.getNexthop() != null && route.getDestination() != null) {
983 boolean isLockAcquired = false;
984 String nextHop = String.valueOf(route.getNexthop().getValue());
985 String destination = String.valueOf(route.getDestination().getValue());
987 String infName = NeutronvpnUtils.getNeutronPortNamefromPortFixedIp(broker, nextHop);
988 logger.trace("Removing extra route with nexthop {}, destination {}, infName {}", nextHop,
989 destination, infName);
990 InstanceIdentifier<Adjacency> adjacencyIdentifier = InstanceIdentifier.builder(VpnInterfaces.class).
991 child(VpnInterface.class, new VpnInterfaceKey(infName)).augmentation(Adjacencies.class)
992 .child(Adjacency.class, new AdjacencyKey(destination)).build();
994 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
995 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, adjacencyIdentifier);
996 logger.trace("extra route {} deleted successfully", route);
997 } catch (Exception e) {
998 logger.error("exception in deleting extra route: {}" + e);
1000 if (isLockAcquired) {
1001 NeutronvpnUtils.unlock(lockManager, infName);
1005 logger.error("Incorrect input received for extra route. {}", route);
1010 protected void removeL3Vpn(Uuid id) {
1012 VpnMap vpnMap = NeutronvpnUtils.getVpnMap(broker, id);
1013 Uuid router = vpnMap.getRouterId();
1014 // dissociate router
1015 if (router != null) {
1016 dissociateRouterFromVpn(id, router);
1018 // dissociate networks
1019 if (!id.equals(router)) {
1020 dissociateNetworksFromVpn(id, vpnMap.getNetworkIds());
1022 // remove entire vpnMaps node
1023 deleteVpnMapsNode(id);
1025 // remove vpn-instance
1026 deleteVpnInstance(id);
1029 protected void removeSubnetFromVpn(Uuid vpnId, Uuid subnet) {
1030 logger.debug("Removing subnet {} from vpn {}", subnet.getValue(), vpnId.getValue());
1031 Subnetmap sn = NeutronvpnUtils.getSubnetmap(broker, subnet);
1032 boolean isLockAcquired = false;
1033 String lockName = vpnId.getValue() + subnet.getValue();
1034 String elanInstanceName = sn.getNetworkId().getValue();
1035 InstanceIdentifier<ElanInstance>elanIdentifierId = InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
1036 Optional<ElanInstance> elanInstance = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId);
1037 long elanTag = elanInstance.get().getElanTag();
1038 Uuid routerId = NeutronvpnUtils.getVpnMap(broker, vpnId).getRouterId();
1039 if (vpnId.equals(routerId)) {
1040 isExternalVpn = false;
1042 isExternalVpn = true;
1045 isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
1046 checkAndPublishSubnetDelNotification(subnet, sn.getSubnetIp(), vpnId.getValue(), isExternalVpn, elanTag);
1047 logger.debug("Subnet removed from Vpn notification sent");
1048 }catch (Exception e){
1049 logger.error("Subnet removed from Vpn notification failed",e);
1051 if (isLockAcquired) {
1052 NeutronvpnUtils.unlock(lockManager, lockName);
1056 // Check if there are ports on this subnet; remove corresponding vpn-interfaces
1057 List<Uuid> portList = sn.getPortList();
1058 if (portList != null) {
1059 for (Uuid port : sn.getPortList()) {
1060 logger.debug("removing vpn-interface for port {}", port.getValue());
1061 deleteVpnInterface(NeutronvpnUtils.getNeutronPort(broker, port));
1062 if (routerId != null) {
1063 removeFromNeutronRouterInterfacesMap(routerId, port.getValue());
1067 // update subnet-vpn association
1068 removeFromSubnetNode(subnet, null, null, vpnId, null);
1070 logger.warn("Subnetmap for subnet {} not found", subnet.getValue());
1074 protected void associateRouterToVpn(Uuid vpnId, Uuid routerId) {
1075 updateVpnMaps(vpnId, null, routerId, null, null);
1076 List<Uuid> routerSubnets = NeutronvpnUtils.getNeutronRouterSubnetIds(broker, routerId);
1077 if (!vpnId.equals(routerId)) {
1078 logger.debug("Updating association of subnets to external vpn {}", vpnId.getValue());
1079 if (routerSubnets != null) {
1080 for (Uuid subnetId : routerSubnets) {
1081 updateVpnForSubnet(vpnId, subnetId,true);
1085 logger.debug("Adding subnets to internal vpn {}", vpnId.getValue());
1086 for (Uuid subnet : routerSubnets) {
1087 addSubnetToVpn(vpnId, subnet);
1092 protected void dissociateRouterFromVpn(Uuid vpnId, Uuid routerId) {
1094 List<Uuid> routerSubnets = NeutronvpnUtils.getNeutronRouterSubnetIds(broker, routerId);
1095 if (routerSubnets != null) {
1096 for (Uuid subnetId : routerSubnets) {
1097 logger.debug("Updating association of subnets to internal vpn {}", routerId.getValue());
1098 updateVpnForSubnet(routerId, subnetId,false);
1101 clearFromVpnMaps(vpnId, routerId, null);
1104 protected List<String> associateNetworksToVpn(Uuid vpn, List<Uuid> networks) {
1105 List<String> failed = new ArrayList<String>();
1106 if (!networks.isEmpty()) {
1107 // store in Data Base
1108 updateVpnMaps(vpn, null, null, null, networks);
1109 // process corresponding subnets for VPN
1110 for (Uuid nw : networks) {
1111 if (NeutronvpnUtils.getNeutronNetwork(broker, nw) == null) {
1112 failed.add(nw.getValue());
1114 List<Uuid> networkSubnets = NeutronvpnUtils.getSubnetIdsFromNetworkId(broker, nw);
1115 logger.debug("Adding network subnets...");
1116 if (networkSubnets != null) {
1117 for (Uuid subnet : networkSubnets) {
1118 addSubnetToVpn(vpn, subnet);
1127 protected List<String> dissociateNetworksFromVpn(Uuid vpn, List<Uuid> networks) {
1128 List<String> failed = new ArrayList<String>();
1129 if (networks != null && !networks.isEmpty()) {
1130 // store in Data Base
1131 clearFromVpnMaps(vpn, null, networks);
1132 // process corresponding subnets for VPN
1133 for (Uuid nw : networks) {
1134 if (NeutronvpnUtils.getNeutronNetwork(broker, nw) == null) {
1135 failed.add(nw.getValue());
1137 List<Uuid> networkSubnets = NeutronvpnUtils.getSubnetIdsFromNetworkId(broker, nw);
1138 logger.debug("Removing network subnets...");
1139 if (networkSubnets != null) {
1140 for (Uuid subnet : networkSubnets) {
1141 removeSubnetFromVpn(vpn, subnet);
1151 public Future<RpcResult<AssociateNetworksOutput>> associateNetworks(AssociateNetworksInput input) {
1153 AssociateNetworksOutputBuilder opBuilder = new AssociateNetworksOutputBuilder();
1154 SettableFuture<RpcResult<AssociateNetworksOutput>> result = SettableFuture.create();
1155 logger.debug("associateNetworks {}", input);
1156 StringBuilder returnMsg = new StringBuilder();
1157 Uuid vpnId = input.getVpnId();
1160 if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
1161 List<Uuid> netIds = input.getNetworkId();
1162 if (netIds != null && !netIds.isEmpty()) {
1163 List<String> failed = associateNetworksToVpn(vpnId, netIds);
1164 if (!failed.isEmpty()) {
1165 returnMsg.append("network(s) not found : ").append(failed);
1169 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1171 if (returnMsg.length() != 0) {
1172 String message = String.format("associate Networks to vpn %s failed due to %s", vpnId.getValue(),
1174 logger.error(message);
1175 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
1177 opBuilder.setResponse(errorResponse);
1178 result.set(RpcResultBuilder.<AssociateNetworksOutput>success().withResult(opBuilder.build()).build());
1180 result.set(RpcResultBuilder.<AssociateNetworksOutput>success().build());
1182 } catch (Exception ex) {
1183 String message = String.format("associate Networks to vpn %s failed due to %s", input.getVpnId().getValue(),
1185 logger.error(message, ex);
1186 result.set(RpcResultBuilder.<AssociateNetworksOutput>failed().withError(ErrorType.APPLICATION, message)
1189 logger.debug("associateNetworks returns..");
1194 public Future<RpcResult<Void>> associateRouter(AssociateRouterInput input) {
1196 SettableFuture<RpcResult<Void>> result = SettableFuture.create();
1197 logger.debug("associateRouter {}", input);
1198 StringBuilder returnMsg = new StringBuilder();
1199 Uuid vpnId = input.getVpnId();
1200 Uuid routerId = input.getRouterId();
1202 if (routerId != null && vpnId != null) {
1203 Router rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
1204 VpnMap vpnMap = NeutronvpnUtils.getVpnMap(broker, vpnId);
1205 if (rtr != null && vpnMap != null) {
1206 if (vpnMap.getRouterId() != null) {
1207 returnMsg.append("vpn ").append(vpnId.getValue()).append(" already associated to router ")
1208 .append(vpnMap.getRouterId().getValue());
1210 associateRouterToVpn(vpnId, routerId);
1213 returnMsg.append("router not found : ").append(routerId.getValue());
1216 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1218 if (returnMsg.length() != 0) {
1219 String message = String.format("associate router to vpn %s failed due to %s", routerId.getValue(),
1221 logger.error(message);
1222 result.set(RpcResultBuilder.<Void>failed().withWarning(ErrorType.PROTOCOL, "invalid-value", message)
1225 result.set(RpcResultBuilder.<Void>success().build());
1227 } catch (Exception ex) {
1228 String message = String.format("associate router %s to vpn %s failed due to %s", routerId.getValue(),
1229 vpnId.getValue(), ex.getMessage());
1230 logger.error(message, ex);
1231 result.set(RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, message).build());
1233 logger.debug("associateRouter returns..");
1238 public Future<RpcResult<DissociateNetworksOutput>> dissociateNetworks(DissociateNetworksInput input) {
1240 DissociateNetworksOutputBuilder opBuilder = new DissociateNetworksOutputBuilder();
1241 SettableFuture<RpcResult<DissociateNetworksOutput>> result = SettableFuture.create();
1243 logger.debug("dissociateNetworks {}", input);
1244 StringBuilder returnMsg = new StringBuilder();
1245 Uuid vpnId = input.getVpnId();
1248 if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
1249 List<Uuid> netIds = input.getNetworkId();
1250 if (netIds != null && !netIds.isEmpty()) {
1251 List<String> failed = dissociateNetworksFromVpn(vpnId, netIds);
1252 if (!failed.isEmpty()) {
1253 returnMsg.append("netowrk(s) not found : ").append(failed);
1257 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1259 if (returnMsg.length() != 0) {
1260 String message = String.format("dissociate Networks to vpn %s failed due to %s", vpnId.getValue(),
1262 logger.error(message);
1263 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
1265 opBuilder.setResponse(errorResponse);
1266 result.set(RpcResultBuilder.<DissociateNetworksOutput>success().withResult(opBuilder.build()).build());
1268 result.set(RpcResultBuilder.<DissociateNetworksOutput>success().build());
1270 } catch (Exception ex) {
1271 String message = String.format("dissociate Networks to vpn %s failed due to %s", input.getVpnId().
1272 getValue(), ex.getMessage());
1273 logger.error(message, ex);
1274 result.set(RpcResultBuilder.<DissociateNetworksOutput>failed().withError(ErrorType.APPLICATION, message)
1277 logger.debug("dissociateNetworks returns..");
1282 public Future<RpcResult<Void>> dissociateRouter(DissociateRouterInput input) {
1284 SettableFuture<RpcResult<Void>> result = SettableFuture.create();
1286 logger.debug("dissociateRouter {}", input);
1287 StringBuilder returnMsg = new StringBuilder();
1288 Uuid vpnId = input.getVpnId();
1289 Uuid routerId = input.getRouterId();
1291 if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
1292 if (routerId != null) {
1293 Router rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
1295 dissociateRouterFromVpn(vpnId, routerId);
1297 returnMsg.append("router not found : ").append(routerId.getValue());
1301 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1303 if (returnMsg.length() != 0) {
1304 String message = String.format("dissociate router %s to vpn %s failed due to %s", routerId.getValue(),
1305 vpnId.getValue(), returnMsg);
1306 logger.error(message);
1307 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
1309 result.set(RpcResultBuilder.<Void>failed().withWarning(ErrorType.PROTOCOL, "invalid-value", message)
1312 result.set(RpcResultBuilder.<Void>success().build());
1314 } catch (Exception ex) {
1315 String message = String.format("disssociate router %s to vpn %s failed due to %s", routerId.getValue(),
1316 vpnId.getValue(), ex.getMessage());
1317 logger.error(message, ex);
1318 result.set(RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, message).build());
1320 logger.debug("dissociateRouter returns..");
1326 public Future<RpcResult<GetFixedIPsForNeutronPortOutput>> getFixedIPsForNeutronPort(GetFixedIPsForNeutronPortInput
1328 GetFixedIPsForNeutronPortOutputBuilder opBuilder = new GetFixedIPsForNeutronPortOutputBuilder();
1329 SettableFuture<RpcResult<GetFixedIPsForNeutronPortOutput>> result = SettableFuture.create();
1330 Uuid portId = input.getPortId();
1331 StringBuilder returnMsg = new StringBuilder();
1333 List<String> fixedIPList = new ArrayList<>();
1334 Port port = NeutronvpnUtils.getNeutronPort(broker, portId);
1336 List<FixedIps> fixedIPs = port.getFixedIps();
1337 for (FixedIps ip : fixedIPs) {
1338 fixedIPList.add(ip.getIpAddress().getIpv4Address().getValue());
1341 returnMsg.append("neutron port: ").append(portId.getValue()).append(" not found");
1343 if (returnMsg.length() != 0) {
1344 String message = String.format("Retrieval of FixedIPList for neutron port failed due to %s", returnMsg);
1345 logger.error(message);
1346 result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>failed().withWarning(ErrorType.PROTOCOL,
1347 "invalid-value", message).build());
1349 opBuilder.setFixedIPs(fixedIPList);
1350 result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>success().withResult(opBuilder.build())
1352 result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>success().build());
1354 } catch (Exception ex) {
1355 String message = String.format("Retrieval of FixedIPList for neutron port %s failed due to %s", portId
1356 .getValue(), ex.getMessage());
1357 logger.error(message, ex);
1358 result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>failed().withError(ErrorType.APPLICATION,
1364 protected void handleNeutronRouterDeleted(Uuid routerId, List<Uuid> routerSubnetIds) {
1365 // check if the router is associated to some VPN
1366 Uuid vpnId = NeutronvpnUtils.getVpnForRouter(broker, routerId, true);
1367 if (vpnId != null) {
1368 // remove existing external vpn interfaces
1369 for (Uuid subnetId : routerSubnetIds) {
1370 removeSubnetFromVpn(vpnId, subnetId);
1372 clearFromVpnMaps(vpnId, routerId, null);
1374 // remove existing internal vpn interfaces
1375 for (Uuid subnetId : routerSubnetIds) {
1376 removeSubnetFromVpn(routerId, subnetId);
1379 // delete entire vpnMaps node for internal VPN
1380 deleteVpnMapsNode(routerId);
1382 // delete vpn-instance for internal VPN
1383 deleteVpnInstance(routerId);
1386 protected Subnet getNeutronSubnet(Uuid subnetId) {
1387 InstanceIdentifier<Subnet> inst = InstanceIdentifier.create(Neutron.class).
1388 child(Subnets.class).child(Subnet.class, new SubnetKey(subnetId));
1389 Optional<Subnet> sn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, inst);
1391 if (sn.isPresent()) {
1397 protected IpAddress getNeutronSubnetGateway(Uuid subnetId) {
1398 Subnet sn = getNeutronSubnet(subnetId);
1400 return sn.getGatewayIp();
1405 protected Port getNeutronPort(String name) {
1406 return NeutronvpnUtils.getNeutronPort(broker, new Uuid(name));
1409 protected Port getNeutronPort(Uuid portId) {
1410 return NeutronvpnUtils.getNeutronPort(broker, portId);
1413 protected List<Uuid> getSubnetsforVpn(Uuid vpnid) {
1414 List<Uuid> subnets = new ArrayList<Uuid>();
1416 InstanceIdentifier<Subnetmaps> subnetmapsid = InstanceIdentifier.builder(Subnetmaps.class).build();
1417 Optional<Subnetmaps> subnetmaps = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
1419 if (subnetmaps.isPresent() && subnetmaps.get().getSubnetmap() != null) {
1420 List<Subnetmap> subnetMapList = subnetmaps.get().getSubnetmap();
1421 for (Subnetmap subnetMap : subnetMapList) {
1422 if (subnetMap.getVpnId() != null && subnetMap.getVpnId().equals(vpnid)) {
1423 subnets.add(subnetMap.getId());
1430 public List<String> showNeutronPortsCLI() {
1431 List<String> result = new ArrayList<String>();
1432 result.add(String.format(" %-34s %-22s %-22s %-6s ", "PortName", "Mac Address", "IP Address",
1434 result.add("---------------------------------------------------------------------------------------");
1435 InstanceIdentifier<Ports> portidentifier = InstanceIdentifier.create(Neutron.class).child(Ports.class);
1437 Optional<Ports> ports = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, portidentifier);
1438 if (ports.isPresent() && ports.get().getPort() != null) {
1439 List<Port> portList = ports.get().getPort();
1440 for (Port port : portList) {
1441 result.add(String.format(" %-34s %-22s %-22s %-6s ", port.getUuid().getValue(), port
1442 .getMacAddress(), port.getFixedIps().get(0).getIpAddress().getIpv4Address().getValue(),
1443 NeutronvpnUtils.getIPPrefixFromPort(broker, port)));
1446 } catch (Exception e) {
1447 logger.error("Failed to retrieve neutronPorts info : ", e);
1448 System.out.println("Failed to retrieve neutronPorts info : " + e.getMessage());
1453 public List<String> showVpnConfigCLI(Uuid vpnuuid) {
1454 List<String> result = new ArrayList<String>();
1455 if (vpnuuid == null) {
1456 System.out.println("");
1457 System.out.println("Displaying VPN config for all VPNs");
1458 System.out.println("To display VPN config for a particular VPN, use the following syntax");
1459 System.out.println(getshowVpnConfigCLIHelp());
1462 RpcResult<GetL3VPNOutput> rpcResult = getL3VPN(new GetL3VPNInputBuilder().setId(vpnuuid).build()).get();
1463 if (rpcResult.isSuccessful()) {
1465 result.add(String.format(" %-37s %-37s %-7s ", "VPN ID", "Tenant ID", "RD"));
1467 result.add(String.format(" %-80s ", "Import-RTs"));
1469 result.add(String.format(" %-80s ", "Export-RTs"));
1471 result.add(String.format(" %-76s ", "Subnet IDs"));
1473 result.add("------------------------------------------------------------------------------------");
1475 List<L3vpnInstances> VpnList = rpcResult.getResult().getL3vpnInstances();
1476 for (L3vpnInstance Vpn : VpnList) {
1477 String tenantId = Vpn.getTenantId() != null ? Vpn.getTenantId().getValue() : "\" " +
1479 result.add(String.format(" %-37s %-37s %-7s ", Vpn.getId().getValue(), tenantId, Vpn
1480 .getRouteDistinguisher()));
1482 result.add(String.format(" %-80s ", Vpn.getImportRT()));
1484 result.add(String.format(" %-80s ", Vpn.getExportRT()));
1487 Uuid vpnid = Vpn.getId();
1488 List<Uuid> subnetList = getSubnetsforVpn(vpnid);
1489 if (!subnetList.isEmpty()) {
1490 for (Uuid subnetuuid : subnetList) {
1491 result.add(String.format(" %-76s ", subnetuuid.getValue()));
1494 result.add(String.format(" %-76s ", "\" \""));
1497 result.add("----------------------------------------");
1501 String errortag = rpcResult.getErrors().iterator().next().getTag();
1502 if (errortag == "") {
1503 System.out.println("");
1504 System.out.println("No VPN has been configured yet");
1505 } else if (errortag == "invalid-value") {
1506 System.out.println("");
1507 System.out.println("VPN " + vpnuuid.getValue() + " is not present");
1509 System.out.println("error getting VPN info : " + rpcResult.getErrors());
1510 System.out.println(getshowVpnConfigCLIHelp());
1513 } catch (InterruptedException | ExecutionException e) {
1514 logger.error("error getting VPN info : ", e);
1515 System.out.println("error getting VPN info : " + e.getMessage());
1520 private String getshowVpnConfigCLIHelp() {
1521 StringBuilder help = new StringBuilder("Usage:");
1522 help.append("display vpn-config [-vid/--vpnid <id>]");
1523 return help.toString();
1526 private void checkAndPublishSubnetAddNotification(Uuid subnetId, String subnetIp, String vpnName, Boolean isExternalvpn, Long elanTag)throws InterruptedException{
1527 SubnetAddedToVpnBuilder builder = new SubnetAddedToVpnBuilder();
1529 logger.info("publish notification called");
1531 builder.setSubnetId(subnetId);
1532 builder.setSubnetIp(subnetIp);
1533 builder.setVpnName(vpnName);
1534 builder.setExternalVpn(isExternalvpn);
1535 builder.setElanTag(elanTag);
1537 notificationPublishService.putNotification(builder.build());
1540 private void checkAndPublishSubnetDelNotification(Uuid subnetId, String subnetIp, String vpnName, Boolean isExternalvpn, Long elanTag)throws InterruptedException{
1541 SubnetDeletedFromVpnBuilder builder = new SubnetDeletedFromVpnBuilder();
1543 logger.info("publish notification called");
1545 builder.setSubnetId(subnetId);
1546 builder.setSubnetIp(subnetIp);
1547 builder.setVpnName(vpnName);
1548 builder.setExternalVpn(isExternalvpn);
1549 builder.setElanTag(elanTag);
1551 notificationPublishService.putNotification(builder.build());
1554 private void checkAndPublishSubnetUpdNotification(Uuid subnetId, String subnetIp, String vpnName, Boolean isExternalvpn, Long elanTag)throws InterruptedException{
1555 SubnetUpdatedInVpnBuilder builder = new SubnetUpdatedInVpnBuilder();
1557 logger.info("publish notification called");
1559 builder.setSubnetId(subnetId);
1560 builder.setSubnetIp(subnetIp);
1561 builder.setVpnName(vpnName);
1562 builder.setExternalVpn(isExternalvpn);
1563 builder.setElanTag(elanTag);
1565 notificationPublishService.putNotification(builder.build());