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;
12 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
13 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
14 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
15 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
16 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil;
17 import org.opendaylight.vpnservice.mdsalutil.interfaces.IMdsalApiManager;
18 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInstances;
19 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInterfaces;
20 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.VpnTargets;
21 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.VpnTargetsBuilder;
22 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.vpntargets.VpnTarget;
23 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.vpntargets
25 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.vpntargets.VpnTargetKey;
26 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstance;
27 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceBuilder;
28 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceKey;
29 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.vpn.instance
31 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterface;
32 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterfaceBuilder;
33 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterfaceKey;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.Adjacencies;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.AdjacenciesBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.adjacency.list.Adjacency;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.adjacency.list.AdjacencyBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.RouterInterfacesMap;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.router.interfaces.map.RouterInterfaces;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.router.interfaces.map.RouterInterfacesBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.router.interfaces.map.RouterInterfacesKey;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.router.interfaces.map.router.interfaces.Interfaces;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.router.interfaces.map.router.interfaces.InterfacesBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.router.interfaces.map.router.interfaces.InterfacesKey;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.adjacency.list.AdjacencyKey;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.l3.attributes.Routes;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.SubnetKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.ElanInstances;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.instances.ElanInstance;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.elan.rev150602.elan.instances.ElanInstanceKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.lockmanager.rev150819.LockManagerService;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.*;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.createl3vpn.input.L3vpn;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.getl3vpn.output.L3vpnInstances;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.getl3vpn.output
67 .L3vpnInstancesBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.subnetmaps.Subnetmap;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.subnetmaps.SubnetmapBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.subnetmaps.SubnetmapKey;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.vpnmaps.VpnMap;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.vpnmaps.VpnMapBuilder;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.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;
79 import java.util.EventListener;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
82 import java.util.ArrayList;
83 import java.util.Arrays;
84 import java.util.List;
85 import java.util.concurrent.ExecutionException;
86 import java.util.concurrent.Future;
88 public class NeutronvpnManager implements NeutronvpnService, AutoCloseable , EventListener{
90 private static final Logger logger = LoggerFactory.getLogger(NeutronvpnManager.class);
91 private final DataBroker broker;
92 private LockManagerService lockManager;
93 IMdsalApiManager mdsalUtil;
94 private NotificationPublishService notificationPublishService;
95 private NotificationService notificationService;
96 Boolean isExternalVpn;
99 * @param db - dataBroker reference
100 * @param mdsalManager - MDSAL Util API access
102 public NeutronvpnManager(final DataBroker db, IMdsalApiManager mdsalManager,NotificationPublishService notiPublishService,
103 NotificationService notiService) {
105 mdsalUtil = mdsalManager;
106 notificationPublishService = notiPublishService;
107 notificationService = notiService;
110 public void setLockManager(LockManagerService lockManager) {
111 this.lockManager = lockManager;
115 public void close() throws Exception {
116 logger.info("Neutron VPN Manager Closed");
119 protected Subnetmap updateSubnetNode(Uuid subnetId, String subnetIp, Uuid tenantId, Uuid networkId, Uuid routerId,
120 Uuid vpnId, Uuid portId) {
121 Subnetmap subnetmap = null;
122 SubnetmapBuilder builder = null;
123 boolean isLockAcquired = false;
124 InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class).
125 child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
127 Optional<Subnetmap> sn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, id);
128 logger.debug("updating Subnet :read: ");
129 if (sn.isPresent()) {
130 builder = new SubnetmapBuilder(sn.get());
131 logger.debug("updating Subnet :existing: ");
133 builder = new SubnetmapBuilder().setKey(new SubnetmapKey(subnetId)).setId(subnetId);
134 logger.debug("updating Subnet :new: ");
137 if (subnetIp != null) {
138 builder.setSubnetIp(subnetIp);
140 if (routerId != null) {
141 builder.setRouterId(routerId);
143 if (networkId != null) {
144 builder.setNetworkId(networkId);
147 builder.setVpnId(vpnId);
149 if (tenantId != null) {
150 builder.setTenantId(tenantId);
153 if (portId != null) {
154 List<Uuid> portList = builder.getPortList();
155 if (portList == null) {
156 portList = new ArrayList<Uuid>();
158 portList.add(portId);
159 builder.setPortList(portList);
162 subnetmap = builder.build();
163 isLockAcquired = NeutronvpnUtils.lock(lockManager, subnetId.getValue());
164 logger.debug("Creating/Updating subnetMap node: {} ", subnetId.getValue());
165 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, subnetmap);
166 } catch (Exception e) {
167 logger.error("Updation of subnetMap failed for node: {}", subnetId.getValue());
169 if (isLockAcquired) {
170 NeutronvpnUtils.unlock(lockManager, subnetId.getValue());
176 protected Subnetmap removeFromSubnetNode(Uuid subnetId, Uuid networkId, Uuid routerId, Uuid vpnId, Uuid portId) {
177 Subnetmap subnetmap = null;
178 boolean isLockAcquired = false;
179 InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class).
180 child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
182 Optional<Subnetmap> sn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, id);
183 if (sn.isPresent()) {
184 SubnetmapBuilder builder = new SubnetmapBuilder(sn.get());
185 if (routerId != null) {
186 builder.setRouterId(null);
188 if (networkId != null) {
189 builder.setNetworkId(null);
192 builder.setVpnId(null);
194 if (portId != null && builder.getPortList() != null) {
195 List<Uuid> portList = builder.getPortList();
196 portList.remove(portId);
197 builder.setPortList(portList);
200 subnetmap = builder.build();
201 isLockAcquired = NeutronvpnUtils.lock(lockManager, subnetId.getValue());
202 logger.debug("Removing from existing subnetmap node: {} ", subnetId.getValue());
203 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, subnetmap);
205 logger.warn("removing from non-existing subnetmap node: {} ", subnetId.getValue());
207 } catch (Exception e) {
208 logger.error("Removal from subnetmap failed for node: {}", subnetId.getValue());
210 if (isLockAcquired) {
211 NeutronvpnUtils.unlock(lockManager, subnetId.getValue());
217 protected void deleteSubnetMapNode(Uuid subnetId) {
218 boolean isLockAcquired = false;
219 InstanceIdentifier<Subnetmap> subnetMapIdentifier = InstanceIdentifier.builder(Subnetmaps.class)
220 .child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
221 logger.debug("removing subnetMap node: {} ", subnetId.getValue());
223 isLockAcquired = NeutronvpnUtils.lock(lockManager, subnetId.getValue());
224 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, subnetMapIdentifier);
225 } catch (Exception e) {
226 logger.error("Delete subnetMap node failed for subnet : {} ", subnetId.getValue());
228 if (isLockAcquired) {
229 NeutronvpnUtils.unlock(lockManager, subnetId.getValue());
234 private void updateVpnInstanceNode(String vpnName, List<String> rd, List<String> irt, List<String> ert) {
236 VpnInstanceBuilder builder = null;
237 List<VpnTarget> vpnTargetList = new ArrayList<VpnTarget>();
238 boolean isLockAcquired = false;
239 InstanceIdentifier<VpnInstance> vpnIdentifier = InstanceIdentifier.builder(VpnInstances.class).
240 child(VpnInstance.class, new VpnInstanceKey(vpnName)).build();
242 Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
244 logger.debug("Creating/Updating a new vpn-instance node: {} ", vpnName);
245 if (optionalVpn.isPresent()) {
246 builder = new VpnInstanceBuilder(optionalVpn.get());
247 logger.debug("updating existing vpninstance node");
249 builder = new VpnInstanceBuilder().setKey(new VpnInstanceKey(vpnName)).setVpnInstanceName(vpnName);
251 if (irt != null && !irt.isEmpty()) {
252 if (ert != null && !ert.isEmpty()) {
253 List<String> commonRT = new ArrayList<String>(irt);
254 commonRT.retainAll(ert);
256 for (String common : commonRT) {
259 VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(common)).setVrfRTValue
260 (common).setVrfRTType(VpnTarget.VrfRTType.Both).build();
261 vpnTargetList.add(vpnTarget);
264 for (String importRT : irt) {
265 VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(importRT)).setVrfRTValue
266 (importRT).setVrfRTType(VpnTarget.VrfRTType.ImportExtcommunity).build();
267 vpnTargetList.add(vpnTarget);
271 if (ert != null && !ert.isEmpty()) {
272 for (String exportRT : ert) {
273 VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(exportRT)).setVrfRTValue
274 (exportRT).setVrfRTType(VpnTarget.VrfRTType.ExportExtcommunity).build();
275 vpnTargetList.add(vpnTarget);
279 VpnTargets vpnTargets = new VpnTargetsBuilder().setVpnTarget(vpnTargetList).build();
281 Ipv4FamilyBuilder ipv4vpnBuilder = new Ipv4FamilyBuilder().setVpnTargets(vpnTargets);
283 if (rd != null && !rd.isEmpty()) {
284 ipv4vpnBuilder.setRouteDistinguisher(rd.get(0));
287 VpnInstance newVpn = builder.setIpv4Family(ipv4vpnBuilder.build()).build();
288 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnName);
289 logger.debug("Creating/Updating vpn-instance for {} ", vpnName);
290 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnIdentifier, newVpn);
291 } catch (Exception e) {
292 logger.error("Update VPN Instance node failed for node: {} {} {} {}", vpnName, rd, irt, ert);
294 if (isLockAcquired) {
295 NeutronvpnUtils.unlock(lockManager, vpnName);
300 private void deleteVpnMapsNode(Uuid vpnid) {
301 boolean isLockAcquired = false;
302 InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
303 .child(VpnMap.class, new VpnMapKey(vpnid)).build();
304 logger.debug("removing vpnMaps node: {} ", vpnid.getValue());
306 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnid.getValue());
307 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
308 } catch (Exception e) {
309 logger.error("Delete vpnMaps node failed for vpn : {} ", vpnid.getValue());
311 if (isLockAcquired) {
312 NeutronvpnUtils.unlock(lockManager, vpnid.getValue());
317 private void updateVpnMaps(Uuid vpnId, String name, Uuid router, Uuid tenantId, List<Uuid> networks) {
318 VpnMapBuilder builder;
319 boolean isLockAcquired = false;
320 InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
321 .child(VpnMap.class, new VpnMapKey(vpnId)).build();
323 Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
325 if (optionalVpnMap.isPresent()) {
326 builder = new VpnMapBuilder(optionalVpnMap.get());
328 builder = new VpnMapBuilder().setKey(new VpnMapKey(vpnId)).setVpnId(vpnId);
332 builder.setName(name);
334 if (tenantId != null) {
335 builder.setTenantId(tenantId);
337 if (router != null) {
338 builder.setRouterId(router);
340 if (networks != null) {
341 List<Uuid> nwList = builder.getNetworkIds();
342 if (nwList == null) {
343 nwList = new ArrayList<Uuid>();
345 nwList.addAll(networks);
346 builder.setNetworkIds(nwList);
349 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
350 logger.debug("Creating/Updating vpnMaps node: {} ", vpnId.getValue());
351 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier, builder.build());
352 logger.debug("VPNMaps DS updated for VPN {} ", vpnId.getValue());
353 } catch (Exception e) {
354 logger.error("UpdateVpnMaps failed for node: {} ", vpnId.getValue());
356 if (isLockAcquired) {
357 NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
362 private void clearFromVpnMaps(Uuid vpnId, Uuid routerId, List<Uuid> networkIds) {
363 boolean isLockAcquired = false;
364 InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
365 .child(VpnMap.class, new VpnMapKey(vpnId)).build();
366 Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
368 if (optionalVpnMap.isPresent()) {
369 VpnMap vpnMap = optionalVpnMap.get();
370 VpnMapBuilder vpnMapBuilder = new VpnMapBuilder(vpnMap);
371 if (routerId != null) {
372 if (vpnMap.getNetworkIds() == null && routerId.equals(vpnMap.getVpnId())) {
374 // remove entire node in case of internal VPN
375 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
376 logger.debug("removing vpnMaps node: {} ", vpnId);
377 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
378 } catch (Exception e) {
379 logger.error("Deletion of vpnMaps node failed for vpn {}", vpnId.getValue());
381 if (isLockAcquired) {
382 NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
387 vpnMapBuilder.setRouterId(null);
389 if (networkIds != null) {
390 List<Uuid> vpnNw = vpnMap.getNetworkIds();
391 for (Uuid nw : networkIds) {
394 if (vpnNw.isEmpty()) {
395 logger.debug("setting networks null in vpnMaps node: {} ", vpnId.getValue());
396 vpnMapBuilder.setNetworkIds(null);
398 vpnMapBuilder.setNetworkIds(vpnNw);
403 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
404 logger.debug("clearing from vpnMaps node: {} ", vpnId.getValue());
405 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier, vpnMapBuilder.build
407 } catch (Exception e) {
408 logger.error("Clearing from vpnMaps node failed for vpn {}", vpnId.getValue());
410 if (isLockAcquired) {
411 NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
415 logger.error("VPN : {} not found", vpnId.getValue());
417 logger.debug("Clear from VPNMaps DS successful for VPN {} ", vpnId.getValue());
420 private void deleteVpnInstance(Uuid vpnId) {
421 boolean isLockAcquired = false;
422 InstanceIdentifier<VpnInstance> vpnIdentifier = InstanceIdentifier.builder(VpnInstances.class).
423 child(VpnInstance.class, new VpnInstanceKey(vpnId.getValue())).build();
425 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
426 logger.debug("Deleting vpnInstance {}", vpnId.getValue());
427 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnIdentifier);
428 } catch (Exception e) {
429 logger.error("Deletion of VPNInstance node failed for VPN {}", vpnId.getValue());
431 if (isLockAcquired) {
432 NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
437 protected void createVpnInterface(Uuid vpnId, Port port) {
438 boolean isLockAcquired = false;
439 if (vpnId == null || port == null) {
442 String infName = port.getUuid().getValue();
443 List<Adjacency> adjList = new ArrayList<Adjacency>();
444 InstanceIdentifier<VpnInterface> vpnIfIdentifier = NeutronvpnUtils.buildVpnInterfaceIdentifier(infName);
446 // find router associated to vpn
447 Uuid routerId = NeutronvpnUtils.getRouterforVpn(broker, vpnId);
449 if (routerId != null) {
450 rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
452 // find all subnets to which this port is associated
453 List<FixedIps> ips = port.getFixedIps();
454 // create adjacency list
455 for (FixedIps ip : ips) {
456 // create vm adjacency
457 StringBuilder IpPrefixBuild = new StringBuilder(ip.getIpAddress().getIpv4Address().getValue());
458 String IpPrefix = IpPrefixBuild.append("/32").toString();
459 Adjacency vmAdj = new AdjacencyBuilder().setKey(new AdjacencyKey(IpPrefix)).setIpAddress(IpPrefix)
460 .setMacAddress(port.getMacAddress()).build();
462 // create extra route adjacency
463 if (rtr != null && rtr.getRoutes() != null) {
464 List<Routes> routeList = rtr.getRoutes();
465 List<Adjacency> erAdjList = addAdjacencyforExtraRoute(routeList, false, infName);
466 if (erAdjList != null && !erAdjList.isEmpty()) {
467 adjList.addAll(erAdjList);
471 // create vpn-interface on this neutron port
472 Adjacencies adjs = new AdjacenciesBuilder().setAdjacency(adjList).build();
473 VpnInterfaceBuilder vpnb = new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(infName)).
474 setName(infName).setVpnInstanceName(vpnId.getValue()).addAugmentation(Adjacencies.class, adjs);
475 VpnInterface vpnIf = vpnb.build();
478 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
479 logger.debug("Creating vpn interface {}", vpnIf);
480 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier, vpnIf);
481 } catch (Exception ex) {
482 logger.error("Creation of vpninterface {} failed due to {}", infName, ex);
484 if (isLockAcquired) {
485 NeutronvpnUtils.unlock(lockManager, infName);
490 protected void deleteVpnInterface(Port port) {
493 boolean isLockAcquired = false;
494 String infName = port.getUuid().getValue();
495 InstanceIdentifier<VpnInterface> vpnIfIdentifier = NeutronvpnUtils.buildVpnInterfaceIdentifier(infName);
498 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
499 logger.debug("Deleting vpn interface {}", infName);
500 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier);
501 } catch (Exception ex) {
502 logger.error("Deletion of vpninterface {} failed due to {}", infName, ex);
504 if (isLockAcquired) {
505 NeutronvpnUtils.unlock(lockManager, infName);
511 protected void updateVpnInterface(Uuid vpnId, Port port) {
512 if (vpnId == null || port == null) {
515 boolean isLockAcquired = false;
516 String infName = port.getUuid().getValue();
517 InstanceIdentifier<VpnInterface> vpnIfIdentifier = NeutronvpnUtils.buildVpnInterfaceIdentifier(infName);
519 Optional<VpnInterface> optionalVpnInterface = NeutronvpnUtils.read(broker, LogicalDatastoreType
520 .CONFIGURATION, vpnIfIdentifier);
521 if (optionalVpnInterface.isPresent()) {
522 VpnInterfaceBuilder vpnIfBuilder = new VpnInterfaceBuilder(optionalVpnInterface.get());
523 VpnInterface vpnIf = vpnIfBuilder.setVpnInstanceName(vpnId.getValue()).build();
524 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
525 logger.debug("Updating vpn interface {}", vpnIf);
526 MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier, vpnIf);
528 logger.error("VPN Interface {} not found", infName);
530 } catch (Exception ex) {
531 logger.error("Updation of vpninterface {} failed due to {}", infName, ex);
533 if (isLockAcquired) {
534 NeutronvpnUtils.unlock(lockManager, infName);
539 public void createL3Vpn(Uuid vpn, String name, Uuid tenant, List<String> rd, List<String> irt, List<String> ert,
540 Uuid router, List<Uuid> networks) {
542 // Update VPN Instance node
543 updateVpnInstanceNode(vpn.getValue(), rd, irt, ert);
545 // Update local vpn-subnet DS
546 updateVpnMaps(vpn, name, router, tenant, networks);
548 if (router != null) {
549 associateRouterToVpn(vpn, router);
551 if (networks != null) {
552 associateNetworksToVpn(vpn, networks);
557 public Future<RpcResult<CreateL3VPNOutput>> createL3VPN(CreateL3VPNInput input) {
559 CreateL3VPNOutputBuilder opBuilder = new CreateL3VPNOutputBuilder();
560 SettableFuture<RpcResult<CreateL3VPNOutput>> result = SettableFuture.create();
561 List<RpcError> errorList = new ArrayList<RpcError>();
562 int failurecount = 0;
563 int warningcount = 0;
565 List<L3vpn> vpns = input.getL3vpn();
566 for (L3vpn vpn : vpns) {
567 RpcError error = null;
569 if (vpn.getRouteDistinguisher() == null || vpn.getImportRT() == null || vpn.getExportRT() == null) {
570 msg = String.format("Creation of L3VPN failed for VPN %s due to absence of RD/iRT/eRT input",
571 vpn.getId().getValue());
573 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
574 errorList.add(error);
578 if (vpn.getRouteDistinguisher().size() > 1) {
579 msg = String.format("Creation of L3VPN failed for VPN %s due to multiple RD input %s",
580 vpn.getId().getValue(), vpn.getRouteDistinguisher());
582 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
583 errorList.add(error);
587 if (vpn.getRouterId() != null) {
588 if (NeutronvpnUtils.getNeutronRouter(broker, vpn.getRouterId()) == null) {
589 msg = String.format("Creation of L3VPN failed for VPN %s due to router not found %s",
590 vpn.getId().getValue(), vpn.getRouterId().getValue());
592 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
593 errorList.add(error);
597 Uuid vpnId = NeutronvpnUtils.getVpnForRouter(broker, vpn.getRouterId(), true);
599 msg = String.format("Creation of L3VPN failed for VPN %s due to router %s already associated to " +
600 "another VPN %s", vpn.getId().getValue(), vpn.getRouterId().getValue(), vpnId.getValue());
602 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
603 errorList.add(error);
608 if (vpn.getNetworkIds() != null) {
609 for (Uuid nw : vpn.getNetworkIds()) {
610 Network network = NeutronvpnUtils.getNeutronNetwork(broker, nw);
611 Uuid vpnId = NeutronvpnUtils.getVpnForNetwork(broker, nw);
612 if (network == null) {
613 msg = String.format("Creation of L3VPN failed for VPN %s due to network not found %s",
614 vpn.getId().getValue(), nw.getValue());
616 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
617 errorList.add(error);
619 } else if (vpnId != null) {
620 msg = String.format("Creation of L3VPN failed for VPN %s due to network %s already associated" +
621 " to another VPN %s", vpn.getId().getValue(), nw.getValue(), vpnId.getValue());
623 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
624 errorList.add(error);
633 createL3Vpn(vpn.getId(), vpn.getName(), vpn.getTenantId(), vpn.getRouteDistinguisher(),
634 vpn.getImportRT(), vpn.getExportRT(), vpn.getRouterId(), vpn.getNetworkIds());
635 } catch (Exception ex) {
636 msg = String.format("Creation of L3VPN failed for VPN %s", vpn.getId().getValue());
637 logger.error(msg, ex);
638 error = RpcResultBuilder.newError(ErrorType.APPLICATION, msg, ex.getMessage());
639 errorList.add(error);
643 // if at least one succeeds; result is success
644 // if none succeeds; result is failure
645 if (failurecount + warningcount == vpns.size()) {
646 result.set(RpcResultBuilder.<CreateL3VPNOutput>failed().withRpcErrors(errorList).build());
648 List<String> errorResponseList = new ArrayList<>();
649 if (!errorList.isEmpty()) {
650 for (RpcError rpcError : errorList) {
651 String errorResponse = String.format("ErrorType: " + rpcError.getErrorType() + ", " + "ErrorTag: " +
652 rpcError.getTag() + ", " + "ErrorMessage: " + rpcError.getMessage());
653 errorResponseList.add(errorResponse);
656 errorResponseList.add("Operation successful with no errors");
658 opBuilder.setResponse(errorResponseList);
659 result.set(RpcResultBuilder.<CreateL3VPNOutput>success().withResult(opBuilder.build()).build());
665 public Future<RpcResult<GetL3VPNOutput>> getL3VPN(GetL3VPNInput input) {
667 GetL3VPNOutputBuilder opBuilder = new GetL3VPNOutputBuilder();
668 SettableFuture<RpcResult<GetL3VPNOutput>> result = SettableFuture.create();
669 Uuid inputVpnId = input.getId();
670 List<VpnInstance> vpns = new ArrayList<VpnInstance>();
673 if (inputVpnId == null) {
675 InstanceIdentifier<VpnInstances> vpnsIdentifier =
676 InstanceIdentifier.builder(VpnInstances.class).build();
677 Optional<VpnInstances> optionalVpns = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
679 if (optionalVpns.isPresent() && optionalVpns.get().getVpnInstance() != null) {
680 for (VpnInstance vpn : optionalVpns.get().getVpnInstance()) {
681 // eliminating internal VPNs from getL3VPN output
682 if (vpn.getIpv4Family().getRouteDistinguisher() != null) {
688 result.set(RpcResultBuilder.<GetL3VPNOutput>failed()
689 .withWarning(ErrorType.PROTOCOL, "", "No VPN is present").build());
693 String name = inputVpnId.getValue();
694 InstanceIdentifier<VpnInstance> vpnIdentifier =
695 InstanceIdentifier.builder(VpnInstances.class)
696 .child(VpnInstance.class, new VpnInstanceKey(name)).build();
697 // read VpnInstance Info
698 Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
700 if (optionalVpn.isPresent()) {
701 vpns.add(optionalVpn.get());
703 String message = String.format("GetL3VPN failed because VPN %s is not present", name);
704 logger.error(message);
705 result.set(RpcResultBuilder.<GetL3VPNOutput>failed()
706 .withWarning(ErrorType.PROTOCOL, "invalid-value", message).build());
709 List<L3vpnInstances> l3vpnList = new ArrayList<L3vpnInstances>();
710 for (VpnInstance vpnInstance : vpns) {
711 Uuid vpnId = new Uuid(vpnInstance.getVpnInstanceName());
713 InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class).child(VpnMap
714 .class, new VpnMapKey(vpnId)).build();
715 L3vpnInstancesBuilder l3vpn = new L3vpnInstancesBuilder();
717 List<String> rd = Arrays.asList(vpnInstance.getIpv4Family().getRouteDistinguisher().split(","));
718 List<VpnTarget> vpnTargetList = vpnInstance.getIpv4Family().getVpnTargets().getVpnTarget();
720 List<String> ertList = new ArrayList<String>();
721 List<String> irtList = new ArrayList<String>();
723 for (VpnTarget vpnTarget : vpnTargetList) {
724 if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.ExportExtcommunity) {
725 ertList.add(vpnTarget.getVrfRTValue());
727 if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.ImportExtcommunity) {
728 irtList.add(vpnTarget.getVrfRTValue());
730 if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.Both) {
731 ertList.add(vpnTarget.getVrfRTValue());
732 irtList.add(vpnTarget.getVrfRTValue());
736 l3vpn.setId(vpnId).setRouteDistinguisher(rd).setImportRT(irtList).setExportRT(ertList);
737 Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
739 if (optionalVpnMap.isPresent()) {
740 VpnMap vpnMap = optionalVpnMap.get();
741 l3vpn.setRouterId(vpnMap.getRouterId()).setNetworkIds(vpnMap.getNetworkIds())
742 .setTenantId(vpnMap.getTenantId()).setName(vpnMap.getName());
744 l3vpnList.add(l3vpn.build());
747 opBuilder.setL3vpnInstances(l3vpnList);
748 result.set(RpcResultBuilder.<GetL3VPNOutput>success().withResult(opBuilder.build()).build());
750 } catch (Exception ex) {
751 String message = String.format("GetL3VPN failed due to %s", ex.getMessage());
752 logger.error(message, ex);
753 result.set(RpcResultBuilder.<GetL3VPNOutput>failed().withError(ErrorType.APPLICATION, message).build());
759 public Future<RpcResult<DeleteL3VPNOutput>> deleteL3VPN(DeleteL3VPNInput input) {
761 DeleteL3VPNOutputBuilder opBuilder = new DeleteL3VPNOutputBuilder();
762 SettableFuture<RpcResult<DeleteL3VPNOutput>> result = SettableFuture.create();
763 List<RpcError> errorList = new ArrayList<RpcError>();
765 int failurecount = 0;
766 int warningcount = 0;
767 List<Uuid> vpns = input.getId();
768 for (Uuid vpn : vpns) {
772 InstanceIdentifier<VpnInstance> vpnIdentifier =
773 InstanceIdentifier.builder(VpnInstances.class)
774 .child(VpnInstance.class, new VpnInstanceKey(vpn.getValue())).build();
775 Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
777 if (optionalVpn.isPresent()) {
780 msg = String.format("VPN with vpnid: %s does not exist", vpn.getValue());
782 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-value", msg);
783 errorList.add(error);
786 } catch (Exception ex) {
787 msg = String.format("Deletion of L3VPN failed when deleting for uuid %s", vpn.getValue());
788 logger.error(msg, ex);
789 error = RpcResultBuilder.newError(ErrorType.APPLICATION, msg, ex.getMessage());
790 errorList.add(error);
794 // if at least one succeeds; result is success
795 // if none succeeds; result is failure
796 if (failurecount + warningcount == vpns.size()) {
797 result.set(RpcResultBuilder.<DeleteL3VPNOutput>failed().withRpcErrors(errorList).build());
799 List<String> errorResponseList = new ArrayList<>();
800 if (!errorList.isEmpty()) {
801 for (RpcError rpcError : errorList) {
802 String errorResponse = String.format("ErrorType: " + rpcError.getErrorType() + ", " + "ErrorTag: " +
803 rpcError.getTag() + ", " + "ErrorMessage: " + rpcError.getMessage());
804 errorResponseList.add(errorResponse);
807 errorResponseList.add("Operation successful with no errors");
809 opBuilder.setResponse(errorResponseList);
810 result.set(RpcResultBuilder.<DeleteL3VPNOutput>success().withResult(opBuilder.build()).build());
815 protected void addSubnetToVpn(Uuid vpnId, Uuid subnet) {
816 logger.debug("Adding subnet {} to vpn {}", subnet.getValue(), vpnId.getValue());
817 Subnetmap sn = updateSubnetNode(subnet, null, null, null, null, vpnId, null);
818 boolean isLockAcquired = false;
819 String lockName = vpnId.getValue() + subnet.getValue();
820 String elanInstanceName = sn.getNetworkId().getValue();
821 InstanceIdentifier<ElanInstance>elanIdentifierId = InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
822 Optional<ElanInstance> elanInstance = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId);
823 long elanTag = elanInstance.get().getElanTag();
824 Uuid routerId = NeutronvpnUtils.getVpnMap(broker, vpnId).getRouterId();
825 if (vpnId.equals(routerId)) {
826 isExternalVpn = false;
828 isExternalVpn = true;
831 isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
832 checkAndPublishSubnetAddNotification(subnet, sn.getSubnetIp(), vpnId.getValue(), isExternalVpn, elanTag);
833 logger.debug("Subnet added to Vpn notification sent");
834 }catch (Exception e){
835 logger.error("Subnet added to Vpn notification failed",e);
837 if (isLockAcquired) {
838 NeutronvpnUtils.unlock(lockManager, lockName);
841 // Check if there are ports on this subnet and add corresponding vpn-interfaces
842 List<Uuid> portList = sn.getPortList();
843 if (portList != null) {
844 for (Uuid port : sn.getPortList()) {
845 logger.debug("adding vpn-interface for port {}", port.getValue());
846 createVpnInterface(vpnId, NeutronvpnUtils.getNeutronPort(broker, port));
851 protected void updateVpnForSubnet(Uuid vpnId, Uuid subnet, boolean isBeingAssociated) {
852 logger.debug("Updating VPN {} for subnet {}", vpnId.getValue(), subnet.getValue());
853 Subnetmap sn = updateSubnetNode(subnet, null, null, null, null, vpnId, null);
854 boolean isLockAcquired = false;
855 String lockName = vpnId.getValue() + subnet.getValue();
856 String elanInstanceName = sn.getNetworkId().getValue();
857 InstanceIdentifier<ElanInstance>elanIdentifierId = InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
858 Optional<ElanInstance> elanInstance = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId);
859 long elanTag = elanInstance.get().getElanTag();
861 isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
862 checkAndPublishSubnetUpdNotification(subnet, sn.getSubnetIp(), vpnId.getValue(), isBeingAssociated, elanTag);
863 logger.debug("Subnet updated in Vpn notification sent");
864 }catch (Exception e){
865 logger.error("Subnet updated in Vpn notification failed",e);
867 if (isLockAcquired) {
868 NeutronvpnUtils.unlock(lockManager, lockName);
871 // Check for ports on this subnet and update association of corresponding vpn-interfaces to external vpn
872 List<Uuid> portList = sn.getPortList();
873 if (portList != null) {
874 for (Uuid port : sn.getPortList()) {
875 logger.debug("Updating vpn-interface for port {}", port.getValue());
876 updateVpnInterface(vpnId, NeutronvpnUtils.getNeutronPort(broker, port));
883 // router-interfaces-map
884 // list router-interfaces {
886 // leaf router-id { type yang:uuid; }
889 // leaf interface-id { type yang:uuid; }
893 InstanceIdentifier<RouterInterfaces> getRouterInterfacesId(Uuid routerId) {
894 return InstanceIdentifier.builder(RouterInterfacesMap.class)
895 .child(RouterInterfaces.class, new RouterInterfacesKey(routerId)).build();
897 void addToNeutronRouterInterfacesMap(Uuid routerId, String interfaceName) {
898 InstanceIdentifier<RouterInterfaces> routerInterfacesId = getRouterInterfacesId(routerId);
899 Optional<RouterInterfaces> optRouterInterfaces = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId);
900 Interfaces routerInterface = new InterfacesBuilder().setKey(new InterfacesKey(interfaceName)).setInterfaceId(interfaceName).build();
901 if(optRouterInterfaces.isPresent()) {
902 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId.child(Interfaces.class, new InterfacesKey(interfaceName)), routerInterface);
904 RouterInterfacesBuilder builder = new RouterInterfacesBuilder().setRouterId(routerId);
905 List<Interfaces> interfaces = new ArrayList<>();
906 interfaces.add(routerInterface);
907 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId, builder.setInterfaces(interfaces).build());
911 void removeFromNeutronRouterInterfacesMap(Uuid routerId, String interfaceName) {
912 InstanceIdentifier<RouterInterfaces> routerInterfacesId = getRouterInterfacesId(routerId);
913 Optional<RouterInterfaces> optRouterInterfaces = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId);
914 Interfaces routerInterface = new InterfacesBuilder().setKey(new InterfacesKey(interfaceName)).setInterfaceId(interfaceName).build();
915 if(optRouterInterfaces.isPresent()) {
916 RouterInterfaces routerInterfaces = optRouterInterfaces.get();
917 List<Interfaces> interfaces = routerInterfaces.getInterfaces();
918 if(interfaces != null && interfaces.remove(routerInterface)) {
919 if(interfaces.isEmpty()) {
920 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId);
922 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId.child(Interfaces.class, new InterfacesKey(interfaceName)));
928 protected List<Adjacency> addAdjacencyforExtraRoute(List<Routes> routeList, boolean rtrUp, String vpnifname) {
929 List<Adjacency> adjList = new ArrayList<Adjacency>();
930 for (Routes route : routeList) {
931 if (route != null && route.getNexthop() != null && route.getDestination() != null) {
932 boolean isLockAcquired = false;
933 String nextHop = String.valueOf(route.getNexthop().getValue());
934 String destination = String.valueOf(route.getDestination().getValue());
936 String infName = NeutronvpnUtils.getNeutronPortNamefromPortFixedIp(broker, nextHop);
937 logger.trace("Adding extra route with nexthop {}, destination {}, infName {}", nextHop,
938 destination, infName);
939 Adjacency erAdj = new AdjacencyBuilder().setIpAddress(destination).setNextHopIp(nextHop).setKey
940 (new AdjacencyKey(destination)).build();
941 if (rtrUp == false) {
942 if (infName.equals(vpnifname)) {
947 InstanceIdentifier<VpnInterface> vpnIfIdentifier = InstanceIdentifier.builder(VpnInterfaces.class).
948 child(VpnInterface.class, new VpnInterfaceKey(infName)).build();
950 Optional<VpnInterface> optionalVpnInterface = NeutronvpnUtils.read(broker, LogicalDatastoreType
951 .CONFIGURATION, vpnIfIdentifier);
952 if (optionalVpnInterface.isPresent()) {
953 Adjacencies erAdjs = new AdjacenciesBuilder().setAdjacency(Arrays.asList(erAdj)).build();
954 VpnInterface vpnIf = new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(infName))
955 .addAugmentation(Adjacencies.class, erAdjs).build();
956 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
957 logger.debug("Adding extra route {}", route);
958 MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier, vpnIf);
960 logger.error("VM adjacency for interface {} not present ; cannot add extra route adjacency",
963 } catch (Exception e) {
964 logger.error("exception in adding extra route: {}" + e);
966 if (isLockAcquired) {
967 NeutronvpnUtils.unlock(lockManager, infName);
971 logger.error("Incorrect input received for extra route. {}", route);
977 protected void removeAdjacencyforExtraRoute(List<Routes> routeList) {
978 for (Routes route : routeList) {
979 if (route != null && route.getNexthop() != null && route.getDestination() != null) {
980 boolean isLockAcquired = false;
981 String nextHop = String.valueOf(route.getNexthop().getValue());
982 String destination = String.valueOf(route.getDestination().getValue());
984 String infName = NeutronvpnUtils.getNeutronPortNamefromPortFixedIp(broker, nextHop);
985 logger.trace("Removing extra route with nexthop {}, destination {}, infName {}", nextHop,
986 destination, infName);
987 InstanceIdentifier<Adjacency> adjacencyIdentifier = InstanceIdentifier.builder(VpnInterfaces.class).
988 child(VpnInterface.class, new VpnInterfaceKey(infName)).augmentation(Adjacencies.class)
989 .child(Adjacency.class, new AdjacencyKey(destination)).build();
991 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
992 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, adjacencyIdentifier);
993 logger.trace("extra route {} deleted successfully", route);
994 } catch (Exception e) {
995 logger.error("exception in deleting extra route: {}" + e);
997 if (isLockAcquired) {
998 NeutronvpnUtils.unlock(lockManager, infName);
1002 logger.error("Incorrect input received for extra route. {}", route);
1007 protected void removeL3Vpn(Uuid id) {
1009 VpnMap vpnMap = NeutronvpnUtils.getVpnMap(broker, id);
1010 Uuid router = vpnMap.getRouterId();
1011 // dissociate router
1012 if (router != null) {
1013 dissociateRouterFromVpn(id, router);
1015 // dissociate networks
1016 if (!id.equals(router)) {
1017 dissociateNetworksFromVpn(id, vpnMap.getNetworkIds());
1019 // remove entire vpnMaps node
1020 deleteVpnMapsNode(id);
1022 // remove vpn-instance
1023 deleteVpnInstance(id);
1026 protected void removeSubnetFromVpn(Uuid vpnId, Uuid subnet) {
1027 logger.debug("Removing subnet {} from vpn {}", subnet.getValue(), vpnId.getValue());
1028 Subnetmap sn = NeutronvpnUtils.getSubnetmap(broker, subnet);
1029 boolean isLockAcquired = false;
1030 String lockName = vpnId.getValue() + subnet.getValue();
1031 String elanInstanceName = sn.getNetworkId().getValue();
1032 InstanceIdentifier<ElanInstance>elanIdentifierId = InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
1033 Optional<ElanInstance> elanInstance = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId);
1034 long elanTag = elanInstance.get().getElanTag();
1035 Uuid routerId = NeutronvpnUtils.getVpnMap(broker, vpnId).getRouterId();
1036 if (vpnId.equals(routerId)) {
1037 isExternalVpn = false;
1039 isExternalVpn = true;
1042 isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
1043 checkAndPublishSubnetDelNotification(subnet, sn.getSubnetIp(), vpnId.getValue(), isExternalVpn, elanTag);
1044 logger.debug("Subnet removed from Vpn notification sent");
1045 }catch (Exception e){
1046 logger.error("Subnet removed from Vpn notification failed",e);
1048 if (isLockAcquired) {
1049 NeutronvpnUtils.unlock(lockManager, lockName);
1053 // Check if there are ports on this subnet; remove corresponding vpn-interfaces
1054 List<Uuid> portList = sn.getPortList();
1055 if (portList != null) {
1056 for (Uuid port : sn.getPortList()) {
1057 logger.debug("removing vpn-interface for port {}", port.getValue());
1058 deleteVpnInterface(NeutronvpnUtils.getNeutronPort(broker, port));
1059 if (routerId != null) {
1060 removeFromNeutronRouterInterfacesMap(routerId, port.getValue());
1064 // update subnet-vpn association
1065 removeFromSubnetNode(subnet, null, null, vpnId, null);
1067 logger.warn("Subnetmap for subnet {} not found", subnet.getValue());
1071 protected void associateRouterToVpn(Uuid vpnId, Uuid routerId) {
1072 updateVpnMaps(vpnId, null, routerId, null, null);
1073 List<Uuid> routerSubnets = NeutronvpnUtils.getNeutronRouterSubnetIds(broker, routerId);
1074 if (!vpnId.equals(routerId)) {
1075 logger.debug("Updating association of subnets to external vpn {}", vpnId.getValue());
1076 if (routerSubnets != null) {
1077 for (Uuid subnetId : routerSubnets) {
1078 updateVpnForSubnet(vpnId, subnetId,true);
1082 logger.debug("Adding subnets to internal vpn {}", vpnId.getValue());
1083 for (Uuid subnet : routerSubnets) {
1084 addSubnetToVpn(vpnId, subnet);
1089 protected void dissociateRouterFromVpn(Uuid vpnId, Uuid routerId) {
1091 List<Uuid> routerSubnets = NeutronvpnUtils.getNeutronRouterSubnetIds(broker, routerId);
1092 if (routerSubnets != null) {
1093 for (Uuid subnetId : routerSubnets) {
1094 logger.debug("Updating association of subnets to internal vpn {}", routerId.getValue());
1095 updateVpnForSubnet(routerId, subnetId,false);
1098 clearFromVpnMaps(vpnId, routerId, null);
1101 protected List<String> associateNetworksToVpn(Uuid vpn, List<Uuid> networks) {
1102 List<String> failed = new ArrayList<String>();
1103 if (!networks.isEmpty()) {
1104 // store in Data Base
1105 updateVpnMaps(vpn, null, null, null, networks);
1106 // process corresponding subnets for VPN
1107 for (Uuid nw : networks) {
1108 if (NeutronvpnUtils.getNeutronNetwork(broker, nw) == null) {
1109 failed.add(nw.getValue());
1111 List<Uuid> networkSubnets = NeutronvpnUtils.getSubnetIdsFromNetworkId(broker, nw);
1112 logger.debug("Adding network subnets...");
1113 if (networkSubnets != null) {
1114 for (Uuid subnet : networkSubnets) {
1115 addSubnetToVpn(vpn, subnet);
1124 protected List<String> dissociateNetworksFromVpn(Uuid vpn, List<Uuid> networks) {
1125 List<String> failed = new ArrayList<String>();
1126 if (networks != null && !networks.isEmpty()) {
1127 // store in Data Base
1128 clearFromVpnMaps(vpn, null, networks);
1129 // process corresponding subnets for VPN
1130 for (Uuid nw : networks) {
1131 if (NeutronvpnUtils.getNeutronNetwork(broker, nw) == null) {
1132 failed.add(nw.getValue());
1134 List<Uuid> networkSubnets = NeutronvpnUtils.getSubnetIdsFromNetworkId(broker, nw);
1135 logger.debug("Removing network subnets...");
1136 if (networkSubnets != null) {
1137 for (Uuid subnet : networkSubnets) {
1138 removeSubnetFromVpn(vpn, subnet);
1148 public Future<RpcResult<AssociateNetworksOutput>> associateNetworks(AssociateNetworksInput input) {
1150 AssociateNetworksOutputBuilder opBuilder = new AssociateNetworksOutputBuilder();
1151 SettableFuture<RpcResult<AssociateNetworksOutput>> result = SettableFuture.create();
1152 logger.debug("associateNetworks {}", input);
1153 StringBuilder returnMsg = new StringBuilder();
1154 Uuid vpnId = input.getVpnId();
1157 if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
1158 List<Uuid> netIds = input.getNetworkId();
1159 if (netIds != null && !netIds.isEmpty()) {
1160 List<String> failed = associateNetworksToVpn(vpnId, netIds);
1161 if (!failed.isEmpty()) {
1162 returnMsg.append("network(s) not found : ").append(failed);
1166 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1168 if (returnMsg.length() != 0) {
1169 String message = String.format("associate Networks to vpn %s failed due to %s", vpnId.getValue(),
1171 logger.error(message);
1172 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
1174 opBuilder.setResponse(errorResponse);
1175 result.set(RpcResultBuilder.<AssociateNetworksOutput>success().withResult(opBuilder.build()).build());
1177 result.set(RpcResultBuilder.<AssociateNetworksOutput>success().build());
1179 } catch (Exception ex) {
1180 String message = String.format("associate Networks to vpn %s failed due to %s", input.getVpnId().getValue(),
1182 logger.error(message, ex);
1183 result.set(RpcResultBuilder.<AssociateNetworksOutput>failed().withError(ErrorType.APPLICATION, message)
1186 logger.debug("associateNetworks returns..");
1191 public Future<RpcResult<Void>> associateRouter(AssociateRouterInput input) {
1193 SettableFuture<RpcResult<Void>> result = SettableFuture.create();
1194 logger.debug("associateRouter {}", input);
1195 StringBuilder returnMsg = new StringBuilder();
1196 Uuid vpnId = input.getVpnId();
1197 Uuid routerId = input.getRouterId();
1199 if (routerId != null && vpnId != null) {
1200 Router rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
1201 VpnMap vpnMap = NeutronvpnUtils.getVpnMap(broker, vpnId);
1202 if (rtr != null && vpnMap != null) {
1203 if (vpnMap.getRouterId() != null) {
1204 returnMsg.append("vpn ").append(vpnId.getValue()).append(" already associated to router ")
1205 .append(vpnMap.getRouterId().getValue());
1207 associateRouterToVpn(vpnId, routerId);
1210 returnMsg.append("router not found : ").append(routerId.getValue());
1213 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1215 if (returnMsg.length() != 0) {
1216 String message = String.format("associate router to vpn %s failed due to %s", routerId.getValue(),
1218 logger.error(message);
1219 result.set(RpcResultBuilder.<Void>failed().withWarning(ErrorType.PROTOCOL, "invalid-value", message)
1222 result.set(RpcResultBuilder.<Void>success().build());
1224 } catch (Exception ex) {
1225 String message = String.format("associate router %s to vpn %s failed due to %s", routerId.getValue(),
1226 vpnId.getValue(), ex.getMessage());
1227 logger.error(message, ex);
1228 result.set(RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, message).build());
1230 logger.debug("associateRouter returns..");
1235 public Future<RpcResult<DissociateNetworksOutput>> dissociateNetworks(DissociateNetworksInput input) {
1237 DissociateNetworksOutputBuilder opBuilder = new DissociateNetworksOutputBuilder();
1238 SettableFuture<RpcResult<DissociateNetworksOutput>> result = SettableFuture.create();
1240 logger.debug("dissociateNetworks {}", input);
1241 StringBuilder returnMsg = new StringBuilder();
1242 Uuid vpnId = input.getVpnId();
1245 if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
1246 List<Uuid> netIds = input.getNetworkId();
1247 if (netIds != null && !netIds.isEmpty()) {
1248 List<String> failed = dissociateNetworksFromVpn(vpnId, netIds);
1249 if (!failed.isEmpty()) {
1250 returnMsg.append("netowrk(s) not found : ").append(failed);
1254 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1256 if (returnMsg.length() != 0) {
1257 String message = String.format("dissociate Networks to vpn %s failed due to %s", vpnId.getValue(),
1259 logger.error(message);
1260 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
1262 opBuilder.setResponse(errorResponse);
1263 result.set(RpcResultBuilder.<DissociateNetworksOutput>success().withResult(opBuilder.build()).build());
1265 result.set(RpcResultBuilder.<DissociateNetworksOutput>success().build());
1267 } catch (Exception ex) {
1268 String message = String.format("dissociate Networks to vpn %s failed due to %s", input.getVpnId().
1269 getValue(), ex.getMessage());
1270 logger.error(message, ex);
1271 result.set(RpcResultBuilder.<DissociateNetworksOutput>failed().withError(ErrorType.APPLICATION, message)
1274 logger.debug("dissociateNetworks returns..");
1279 public Future<RpcResult<Void>> dissociateRouter(DissociateRouterInput input) {
1281 SettableFuture<RpcResult<Void>> result = SettableFuture.create();
1283 logger.debug("dissociateRouter {}", input);
1284 StringBuilder returnMsg = new StringBuilder();
1285 Uuid vpnId = input.getVpnId();
1286 Uuid routerId = input.getRouterId();
1288 if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
1289 if (routerId != null) {
1290 Router rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
1292 dissociateRouterFromVpn(vpnId, routerId);
1294 returnMsg.append("router not found : ").append(routerId.getValue());
1298 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1300 if (returnMsg.length() != 0) {
1301 String message = String.format("dissociate router %s to vpn %s failed due to %s", routerId.getValue(),
1302 vpnId.getValue(), returnMsg);
1303 logger.error(message);
1304 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
1306 result.set(RpcResultBuilder.<Void>failed().withWarning(ErrorType.PROTOCOL, "invalid-value", message)
1309 result.set(RpcResultBuilder.<Void>success().build());
1311 } catch (Exception ex) {
1312 String message = String.format("disssociate router %s to vpn %s failed due to %s", routerId.getValue(),
1313 vpnId.getValue(), ex.getMessage());
1314 logger.error(message, ex);
1315 result.set(RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, message).build());
1317 logger.debug("dissociateRouter returns..");
1323 public Future<RpcResult<GetFixedIPsForNeutronPortOutput>> getFixedIPsForNeutronPort(GetFixedIPsForNeutronPortInput
1325 GetFixedIPsForNeutronPortOutputBuilder opBuilder = new GetFixedIPsForNeutronPortOutputBuilder();
1326 SettableFuture<RpcResult<GetFixedIPsForNeutronPortOutput>> result = SettableFuture.create();
1327 Uuid portId = input.getPortId();
1328 StringBuilder returnMsg = new StringBuilder();
1330 List<String> fixedIPList = new ArrayList<>();
1331 Port port = NeutronvpnUtils.getNeutronPort(broker, portId);
1333 List<FixedIps> fixedIPs = port.getFixedIps();
1334 for (FixedIps ip : fixedIPs) {
1335 fixedIPList.add(ip.getIpAddress().getIpv4Address().getValue());
1338 returnMsg.append("neutron port: ").append(portId.getValue()).append(" not found");
1340 if (returnMsg.length() != 0) {
1341 String message = String.format("Retrieval of FixedIPList for neutron port failed due to %s", returnMsg);
1342 logger.error(message);
1343 result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>failed().withWarning(ErrorType.PROTOCOL,
1344 "invalid-value", message).build());
1346 opBuilder.setFixedIPs(fixedIPList);
1347 result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>success().withResult(opBuilder.build())
1349 result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>success().build());
1351 } catch (Exception ex) {
1352 String message = String.format("Retrieval of FixedIPList for neutron port %s failed due to %s", portId
1353 .getValue(), ex.getMessage());
1354 logger.error(message, ex);
1355 result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>failed().withError(ErrorType.APPLICATION,
1361 protected void handleNeutronRouterDeleted(Uuid routerId, List<Uuid> routerSubnetIds) {
1362 // check if the router is associated to some VPN
1363 Uuid vpnId = NeutronvpnUtils.getVpnForRouter(broker, routerId, true);
1364 if (vpnId != null) {
1365 // remove existing external vpn interfaces
1366 for (Uuid subnetId : routerSubnetIds) {
1367 removeSubnetFromVpn(vpnId, subnetId);
1369 clearFromVpnMaps(vpnId, routerId, null);
1371 // remove existing internal vpn interfaces
1372 for (Uuid subnetId : routerSubnetIds) {
1373 removeSubnetFromVpn(routerId, subnetId);
1376 // delete entire vpnMaps node for internal VPN
1377 deleteVpnMapsNode(routerId);
1379 // delete vpn-instance for internal VPN
1380 deleteVpnInstance(routerId);
1383 protected Subnet getNeutronSubnet(Uuid subnetId) {
1384 InstanceIdentifier<Subnet> inst = InstanceIdentifier.create(Neutron.class).
1385 child(Subnets.class).child(Subnet.class, new SubnetKey(subnetId));
1386 Optional<Subnet> sn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, inst);
1388 if (sn.isPresent()) {
1394 protected IpAddress getNeutronSubnetGateway(Uuid subnetId) {
1395 Subnet sn = getNeutronSubnet(subnetId);
1397 return sn.getGatewayIp();
1402 protected Port getNeutronPort(String name) {
1403 return NeutronvpnUtils.getNeutronPort(broker, new Uuid(name));
1406 protected Port getNeutronPort(Uuid portId) {
1407 return NeutronvpnUtils.getNeutronPort(broker, portId);
1410 protected List<Uuid> getSubnetsforVpn(Uuid vpnid) {
1411 List<Uuid> subnets = new ArrayList<Uuid>();
1413 InstanceIdentifier<Subnetmaps> subnetmapsid = InstanceIdentifier.builder(Subnetmaps.class).build();
1414 Optional<Subnetmaps> subnetmaps = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
1416 if (subnetmaps.isPresent() && subnetmaps.get().getSubnetmap() != null) {
1417 List<Subnetmap> subnetMapList = subnetmaps.get().getSubnetmap();
1418 for (Subnetmap subnetMap : subnetMapList) {
1419 if (subnetMap.getVpnId() != null && subnetMap.getVpnId().equals(vpnid)) {
1420 subnets.add(subnetMap.getId());
1427 public List<String> showNeutronPortsCLI() {
1428 List<String> result = new ArrayList<String>();
1429 result.add(String.format(" %-34s %-22s %-22s %-6s ", "PortName", "Mac Address", "IP Address",
1431 result.add("---------------------------------------------------------------------------------------");
1432 InstanceIdentifier<Ports> portidentifier = InstanceIdentifier.create(Neutron.class).child(Ports.class);
1434 Optional<Ports> ports = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, portidentifier);
1435 if (ports.isPresent() && ports.get().getPort() != null) {
1436 List<Port> portList = ports.get().getPort();
1437 for (Port port : portList) {
1438 result.add(String.format(" %-34s %-22s %-22s %-6s ", port.getUuid().getValue(), port
1439 .getMacAddress(), port.getFixedIps().get(0).getIpAddress().getIpv4Address().getValue(),
1440 NeutronvpnUtils.getIPPrefixFromPort(broker, port)));
1443 } catch (Exception e) {
1444 logger.error("Failed to retrieve neutronPorts info : ", e);
1445 System.out.println("Failed to retrieve neutronPorts info : " + e.getMessage());
1450 public List<String> showVpnConfigCLI(Uuid vpnuuid) {
1451 List<String> result = new ArrayList<String>();
1452 if (vpnuuid == null) {
1453 System.out.println("");
1454 System.out.println("Displaying VPN config for all VPNs");
1455 System.out.println("To display VPN config for a particular VPN, use the following syntax");
1456 System.out.println(getshowVpnConfigCLIHelp());
1459 RpcResult<GetL3VPNOutput> rpcResult = getL3VPN(new GetL3VPNInputBuilder().setId(vpnuuid).build()).get();
1460 if (rpcResult.isSuccessful()) {
1462 result.add(String.format(" %-37s %-37s %-7s ", "VPN ID", "Tenant ID", "RD"));
1464 result.add(String.format(" %-80s ", "Import-RTs"));
1466 result.add(String.format(" %-80s ", "Export-RTs"));
1468 result.add(String.format(" %-76s ", "Subnet IDs"));
1470 result.add("------------------------------------------------------------------------------------");
1472 List<L3vpnInstances> VpnList = rpcResult.getResult().getL3vpnInstances();
1473 for (L3vpnInstance Vpn : VpnList) {
1474 String tenantId = Vpn.getTenantId() != null ? Vpn.getTenantId().getValue() : "\" " +
1476 result.add(String.format(" %-37s %-37s %-7s ", Vpn.getId().getValue(), tenantId, Vpn
1477 .getRouteDistinguisher()));
1479 result.add(String.format(" %-80s ", Vpn.getImportRT()));
1481 result.add(String.format(" %-80s ", Vpn.getExportRT()));
1484 Uuid vpnid = Vpn.getId();
1485 List<Uuid> subnetList = getSubnetsforVpn(vpnid);
1486 if (!subnetList.isEmpty()) {
1487 for (Uuid subnetuuid : subnetList) {
1488 result.add(String.format(" %-76s ", subnetuuid.getValue()));
1491 result.add(String.format(" %-76s ", "\" \""));
1494 result.add("----------------------------------------");
1498 String errortag = rpcResult.getErrors().iterator().next().getTag();
1499 if (errortag == "") {
1500 System.out.println("");
1501 System.out.println("No VPN has been configured yet");
1502 } else if (errortag == "invalid-value") {
1503 System.out.println("");
1504 System.out.println("VPN " + vpnuuid.getValue() + " is not present");
1506 System.out.println("error getting VPN info : " + rpcResult.getErrors());
1507 System.out.println(getshowVpnConfigCLIHelp());
1510 } catch (InterruptedException | ExecutionException e) {
1511 logger.error("error getting VPN info : ", e);
1512 System.out.println("error getting VPN info : " + e.getMessage());
1517 private String getshowVpnConfigCLIHelp() {
1518 StringBuilder help = new StringBuilder("Usage:");
1519 help.append("display vpn-config [-vid/--vpnid <id>]");
1520 return help.toString();
1523 private void checkAndPublishSubnetAddNotification(Uuid subnetId, String subnetIp, String vpnName, Boolean isExternalvpn, Long elanTag)throws InterruptedException{
1524 SubnetAddedToVpnBuilder builder = new SubnetAddedToVpnBuilder();
1526 logger.info("publish notification called");
1528 builder.setSubnetId(subnetId);
1529 builder.setSubnetIp(subnetIp);
1530 builder.setVpnName(vpnName);
1531 builder.setExternalVpn(isExternalvpn);
1532 builder.setElanTag(elanTag);
1534 notificationPublishService.putNotification(builder.build());
1537 private void checkAndPublishSubnetDelNotification(Uuid subnetId, String subnetIp, String vpnName, Boolean isExternalvpn, Long elanTag)throws InterruptedException{
1538 SubnetDeletedFromVpnBuilder builder = new SubnetDeletedFromVpnBuilder();
1540 logger.info("publish notification called");
1542 builder.setSubnetId(subnetId);
1543 builder.setSubnetIp(subnetIp);
1544 builder.setVpnName(vpnName);
1545 builder.setExternalVpn(isExternalvpn);
1546 builder.setElanTag(elanTag);
1548 notificationPublishService.putNotification(builder.build());
1551 private void checkAndPublishSubnetUpdNotification(Uuid subnetId, String subnetIp, String vpnName, Boolean isExternalvpn, Long elanTag)throws InterruptedException{
1552 SubnetUpdatedInVpnBuilder builder = new SubnetUpdatedInVpnBuilder();
1554 logger.info("publish notification called");
1556 builder.setSubnetId(subnetId);
1557 builder.setSubnetIp(subnetIp);
1558 builder.setVpnName(vpnName);
1559 builder.setExternalVpn(isExternalvpn);
1560 builder.setElanTag(elanTag);
1562 notificationPublishService.putNotification(builder.build());