Merge "Clean up pom files"
[netvirt.git] / vpnservice / neutronvpn / neutronvpn-impl / src / main / java / org / opendaylight / netvirt / neutronvpn / NeutronvpnManager.java
1 /*
2  * Copyright (c) 2015 - 2016 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netvirt.neutronvpn;
9
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.SettableFuture;
12
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
25         .VpnTargetBuilder;
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
31         .Ipv4FamilyBuilder;
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.ext.rev150712.NetworkL3Extension;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.l3.attributes.Routes;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.SubnetKey;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.*;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.createl3vpn.input.L3vpn;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.getl3vpn.output.L3vpnInstances;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.getl3vpn.output
68         .L3vpnInstancesBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapBuilder;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapKey;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpnmaps.VpnMap;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpnmaps.VpnMapBuilder;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.vpnmaps.VpnMapKey;
75 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
76 import org.opendaylight.yangtools.yang.common.RpcError;
77 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
78 import org.opendaylight.yangtools.yang.common.RpcResult;
79 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
80
81 import java.util.EventListener;
82
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85
86 import java.util.ArrayList;
87 import java.util.Arrays;
88 import java.util.List;
89 import java.util.concurrent.ConcurrentHashMap;
90 import java.util.concurrent.ExecutionException;
91 import java.util.concurrent.Future;
92
93 public class NeutronvpnManager implements NeutronvpnService, AutoCloseable , EventListener{
94
95     private static final Logger logger = LoggerFactory.getLogger(NeutronvpnManager.class);
96     private final DataBroker broker;
97     private LockManagerService lockManager;
98     private NeutronvpnNatManager nvpnNatManager;
99     IMdsalApiManager mdsalUtil;
100     private NotificationPublishService notificationPublishService;
101     private NotificationService notificationService;
102     Boolean isExternalVpn;
103
104     /**
105      * @param db           - dataBroker reference
106      * @param mdsalManager - MDSAL Util API access
107      */
108     public NeutronvpnManager(final DataBroker db, IMdsalApiManager mdsalManager,NotificationPublishService notiPublishService,
109                              NotificationService notiService, NeutronvpnNatManager vpnNatMgr) {
110         broker = db;
111         mdsalUtil = mdsalManager;
112         nvpnNatManager = vpnNatMgr;
113         notificationPublishService = notiPublishService;
114         notificationService = notiService;
115     }
116
117     public void setLockManager(LockManagerService lockManager) {
118         this.lockManager = lockManager;
119     }
120
121     @Override
122     public void close() throws Exception {
123         logger.info("Neutron VPN Manager Closed");
124     }
125
126     protected Subnetmap updateSubnetNode(Uuid subnetId, String subnetIp, Uuid tenantId, Uuid networkId, Uuid routerId,
127                                          Uuid vpnId, Uuid portId) {
128         Subnetmap subnetmap = null;
129         SubnetmapBuilder builder = null;
130         boolean isLockAcquired = false;
131         InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class).
132                 child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
133         try {
134             Optional<Subnetmap> sn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, id);
135             logger.debug("updating Subnet :read: ");
136             if (sn.isPresent()) {
137                 builder = new SubnetmapBuilder(sn.get());
138                 logger.debug("updating Subnet :existing: ");
139             } else {
140                 builder = new SubnetmapBuilder().setKey(new SubnetmapKey(subnetId)).setId(subnetId);
141                 logger.debug("updating Subnet :new: ");
142             }
143
144             if (subnetIp != null) {
145                 builder.setSubnetIp(subnetIp);
146             }
147             if (routerId != null) {
148                 builder.setRouterId(routerId);
149             }
150             if (networkId != null) {
151                 builder.setNetworkId(networkId);
152             }
153             if (vpnId != null) {
154                 builder.setVpnId(vpnId);
155             }
156             if (tenantId != null) {
157                 builder.setTenantId(tenantId);
158             }
159
160             if (portId != null) {
161                 List<Uuid> portList = builder.getPortList();
162                 if (portList == null) {
163                     portList = new ArrayList<>();
164                 }
165                 portList.add(portId);
166                 builder.setPortList(portList);
167             }
168
169             subnetmap = builder.build();
170             isLockAcquired = NeutronvpnUtils.lock(lockManager, subnetId.getValue());
171             logger.debug("Creating/Updating subnetMap node: {} ", subnetId.getValue());
172             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, subnetmap);
173         } catch (Exception e) {
174             logger.error("Updation of subnetMap failed for node: {}", subnetId.getValue());
175         } finally {
176             if (isLockAcquired) {
177                 NeutronvpnUtils.unlock(lockManager, subnetId.getValue());
178             }
179         }
180         return subnetmap;
181     }
182
183     protected Subnetmap removeFromSubnetNode(Uuid subnetId, Uuid networkId, Uuid routerId, Uuid vpnId, Uuid portId) {
184         Subnetmap subnetmap = null;
185         boolean isLockAcquired = false;
186         InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class).
187                 child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
188         try {
189             Optional<Subnetmap> sn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, id);
190             if (sn.isPresent()) {
191                 SubnetmapBuilder builder = new SubnetmapBuilder(sn.get());
192                 if (routerId != null) {
193                     builder.setRouterId(null);
194                 }
195                 if (networkId != null) {
196                     builder.setNetworkId(null);
197                 }
198                 if (vpnId != null) {
199                     builder.setVpnId(null);
200                 }
201                 if (portId != null && builder.getPortList() != null) {
202                     List<Uuid> portList = builder.getPortList();
203                     portList.remove(portId);
204                     builder.setPortList(portList);
205                 }
206
207                 subnetmap = builder.build();
208                 isLockAcquired = NeutronvpnUtils.lock(lockManager, subnetId.getValue());
209                 logger.debug("Removing from existing subnetmap node: {} ", subnetId.getValue());
210                 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, subnetmap);
211             } else {
212                 logger.warn("removing from non-existing subnetmap node: {} ", subnetId.getValue());
213             }
214         } catch (Exception e) {
215             logger.error("Removal from subnetmap failed for node: {}", subnetId.getValue());
216         } finally {
217             if (isLockAcquired) {
218                 NeutronvpnUtils.unlock(lockManager, subnetId.getValue());
219             }
220         }
221         return subnetmap;
222     }
223
224     protected void deleteSubnetMapNode(Uuid subnetId) {
225         boolean isLockAcquired = false;
226         InstanceIdentifier<Subnetmap> subnetMapIdentifier = InstanceIdentifier.builder(Subnetmaps.class)
227                 .child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
228         logger.debug("removing subnetMap node: {} ", subnetId.getValue());
229         try {
230             isLockAcquired = NeutronvpnUtils.lock(lockManager, subnetId.getValue());
231             MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, subnetMapIdentifier);
232         } catch (Exception e) {
233             logger.error("Delete subnetMap node failed for subnet : {} ", subnetId.getValue());
234         } finally {
235             if (isLockAcquired) {
236                 NeutronvpnUtils.unlock(lockManager, subnetId.getValue());
237             }
238         }
239     }
240
241     private void updateVpnInstanceNode(String vpnName, List<String> rd, List<String> irt, List<String> ert) {
242
243         VpnInstanceBuilder builder = null;
244         List<VpnTarget> vpnTargetList = new ArrayList<>();
245         boolean isLockAcquired = false;
246         InstanceIdentifier<VpnInstance> vpnIdentifier = InstanceIdentifier.builder(VpnInstances.class).
247                 child(VpnInstance.class, new VpnInstanceKey(vpnName)).build();
248         try {
249             Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
250                     vpnIdentifier);
251             logger.debug("Creating/Updating a new vpn-instance node: {} ", vpnName);
252             if (optionalVpn.isPresent()) {
253                 builder = new VpnInstanceBuilder(optionalVpn.get());
254                 logger.debug("updating existing vpninstance node");
255             } else {
256                 builder = new VpnInstanceBuilder().setKey(new VpnInstanceKey(vpnName)).setVpnInstanceName(vpnName);
257             }
258             if (irt != null && !irt.isEmpty()) {
259                 if (ert != null && !ert.isEmpty()) {
260                     List<String> commonRT = new ArrayList<>(irt);
261                     commonRT.retainAll(ert);
262
263                     for (String common : commonRT) {
264                         irt.remove(common);
265                         ert.remove(common);
266                         VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(common)).setVrfRTValue
267                                 (common).setVrfRTType(VpnTarget.VrfRTType.Both).build();
268                         vpnTargetList.add(vpnTarget);
269                     }
270                 }
271                 for (String importRT : irt) {
272                     VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(importRT)).setVrfRTValue
273                             (importRT).setVrfRTType(VpnTarget.VrfRTType.ImportExtcommunity).build();
274                     vpnTargetList.add(vpnTarget);
275                 }
276             }
277
278             if (ert != null && !ert.isEmpty()) {
279                 for (String exportRT : ert) {
280                     VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(exportRT)).setVrfRTValue
281                             (exportRT).setVrfRTType(VpnTarget.VrfRTType.ExportExtcommunity).build();
282                     vpnTargetList.add(vpnTarget);
283                 }
284             }
285
286             VpnTargets vpnTargets = new VpnTargetsBuilder().setVpnTarget(vpnTargetList).build();
287
288             Ipv4FamilyBuilder ipv4vpnBuilder = new Ipv4FamilyBuilder().setVpnTargets(vpnTargets);
289
290             if (rd != null && !rd.isEmpty()) {
291                 ipv4vpnBuilder.setRouteDistinguisher(rd.get(0));
292             }
293
294             VpnInstance newVpn = builder.setIpv4Family(ipv4vpnBuilder.build()).build();
295             isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnName);
296             logger.debug("Creating/Updating vpn-instance for {} ", vpnName);
297             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnIdentifier, newVpn);
298         } catch (Exception e) {
299             logger.error("Update VPN Instance node failed for node: {} {} {} {}", vpnName, rd, irt, ert);
300         } finally {
301             if (isLockAcquired) {
302                 NeutronvpnUtils.unlock(lockManager, vpnName);
303             }
304         }
305     }
306
307     private void deleteVpnMapsNode(Uuid vpnid) {
308         boolean isLockAcquired = false;
309         InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
310                 .child(VpnMap.class, new VpnMapKey(vpnid)).build();
311         logger.debug("removing vpnMaps node: {} ", vpnid.getValue());
312         try {
313             isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnid.getValue());
314             MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
315         } catch (Exception e) {
316             logger.error("Delete vpnMaps node failed for vpn : {} ", vpnid.getValue());
317         } finally {
318             if (isLockAcquired) {
319                 NeutronvpnUtils.unlock(lockManager, vpnid.getValue());
320             }
321         }
322     }
323
324     private void updateVpnMaps(Uuid vpnId, String name, Uuid router, Uuid tenantId, List<Uuid> networks) {
325         VpnMapBuilder builder;
326         boolean isLockAcquired = false;
327         InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
328                 .child(VpnMap.class, new VpnMapKey(vpnId)).build();
329         try {
330             Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
331                     vpnMapIdentifier);
332             if (optionalVpnMap.isPresent()) {
333                 builder = new VpnMapBuilder(optionalVpnMap.get());
334             } else {
335                 builder = new VpnMapBuilder().setKey(new VpnMapKey(vpnId)).setVpnId(vpnId);
336             }
337
338             if (name != null) {
339                 builder.setName(name);
340             }
341             if (tenantId != null) {
342                 builder.setTenantId(tenantId);
343             }
344             if (router != null) {
345                 builder.setRouterId(router);
346             }
347             if (networks != null) {
348                 List<Uuid> nwList = builder.getNetworkIds();
349                 if (nwList == null) {
350                     nwList = new ArrayList<>();
351                 }
352                 nwList.addAll(networks);
353                 builder.setNetworkIds(nwList);
354             }
355
356             isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
357             logger.debug("Creating/Updating vpnMaps node: {} ", vpnId.getValue());
358             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier, builder.build());
359             logger.debug("VPNMaps DS updated for VPN {} ", vpnId.getValue());
360         } catch (Exception e) {
361             logger.error("UpdateVpnMaps failed for node: {} ", vpnId.getValue());
362         } finally {
363             if (isLockAcquired) {
364                 NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
365             }
366         }
367     }
368
369     private void clearFromVpnMaps(Uuid vpnId, Uuid routerId, List<Uuid> networkIds) {
370         boolean isLockAcquired = false;
371         InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
372                 .child(VpnMap.class, new VpnMapKey(vpnId)).build();
373         Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
374                 vpnMapIdentifier);
375         if (optionalVpnMap.isPresent()) {
376             VpnMap vpnMap = optionalVpnMap.get();
377             VpnMapBuilder vpnMapBuilder = new VpnMapBuilder(vpnMap);
378             if (routerId != null) {
379                 if (vpnMap.getNetworkIds() == null && routerId.equals(vpnMap.getVpnId())) {
380                     try {
381                         // remove entire node in case of internal VPN
382                         isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
383                         logger.debug("removing vpnMaps node: {} ", vpnId);
384                         MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
385                     } catch (Exception e) {
386                         logger.error("Deletion of vpnMaps node failed for vpn {}", vpnId.getValue());
387                     } finally {
388                         if (isLockAcquired) {
389                             NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
390                         }
391                     }
392                     return;
393                 }
394                 vpnMapBuilder.setRouterId(null);
395             }
396             if (networkIds != null) {
397                 List<Uuid> vpnNw = vpnMap.getNetworkIds();
398                 for (Uuid nw : networkIds) {
399                     vpnNw.remove(nw);
400                 }
401                 if (vpnNw.isEmpty()) {
402                     logger.debug("setting networks null in vpnMaps node: {} ", vpnId.getValue());
403                     vpnMapBuilder.setNetworkIds(null);
404                 } else {
405                     vpnMapBuilder.setNetworkIds(vpnNw);
406                 }
407             }
408
409             try {
410                 isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
411                 logger.debug("clearing from vpnMaps node: {} ", vpnId.getValue());
412                 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier, vpnMapBuilder.build
413                         ());
414             } catch (Exception e) {
415                 logger.error("Clearing from vpnMaps node failed for vpn {}", vpnId.getValue());
416             } finally {
417                 if (isLockAcquired) {
418                     NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
419                 }
420             }
421         } else {
422             logger.error("VPN : {} not found", vpnId.getValue());
423         }
424         logger.debug("Clear from VPNMaps DS successful for VPN {} ", vpnId.getValue());
425     }
426
427     private void deleteVpnInstance(Uuid vpnId) {
428         boolean isLockAcquired = false;
429         InstanceIdentifier<VpnInstance> vpnIdentifier = InstanceIdentifier.builder(VpnInstances.class).
430                 child(VpnInstance.class, new VpnInstanceKey(vpnId.getValue())).build();
431         try {
432             isLockAcquired = NeutronvpnUtils.lock(lockManager, vpnId.getValue());
433             logger.debug("Deleting vpnInstance {}", vpnId.getValue());
434             MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnIdentifier);
435         } catch (Exception e) {
436             logger.error("Deletion of VPNInstance node failed for VPN {}", vpnId.getValue());
437         } finally {
438             if (isLockAcquired) {
439                 NeutronvpnUtils.unlock(lockManager, vpnId.getValue());
440             }
441         }
442     }
443
444     protected void createVpnInterface(Uuid vpnId, Port port) {
445         boolean isLockAcquired = false;
446         if (vpnId == null || port == null) {
447             return;
448         }
449         String infName = port.getUuid().getValue();
450         List<Adjacency> adjList = new ArrayList<>();
451         InstanceIdentifier<VpnInterface> vpnIfIdentifier = NeutronvpnUtils.buildVpnInterfaceIdentifier(infName);
452
453         // find router associated to vpn
454         Uuid routerId = NeutronvpnUtils.getRouterforVpn(broker, vpnId);
455         Router rtr = null;
456         if (routerId != null) {
457             rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
458         }
459         // find all subnets to which this port is associated
460         List<FixedIps> ips = port.getFixedIps();
461         // create adjacency list
462         for (FixedIps ip : ips) {
463             // create vm adjacency
464             StringBuilder IpPrefixBuild = new StringBuilder(ip.getIpAddress().getIpv4Address().getValue());
465             String IpPrefix = IpPrefixBuild.append("/32").toString();
466             Adjacency vmAdj = new AdjacencyBuilder().setKey(new AdjacencyKey(IpPrefix)).setIpAddress(IpPrefix)
467                     .setMacAddress(port.getMacAddress().getValue()).build();
468             adjList.add(vmAdj);
469             // create extra route adjacency
470             if (rtr != null && rtr.getRoutes() != null) {
471                 List<Routes> routeList = rtr.getRoutes();
472                 List<Adjacency> erAdjList = addAdjacencyforExtraRoute(routeList, false, infName);
473                 if (erAdjList != null && !erAdjList.isEmpty()) {
474                     adjList.addAll(erAdjList);
475                 }
476             }
477         }
478         // create vpn-interface on this neutron port
479         Adjacencies adjs = new AdjacenciesBuilder().setAdjacency(adjList).build();
480         VpnInterfaceBuilder vpnb = new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(infName)).
481                 setName(infName).setVpnInstanceName(vpnId.getValue()).addAugmentation(Adjacencies.class, adjs);
482         VpnInterface vpnIf = vpnb.build();
483
484         try {
485             isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
486             logger.debug("Creating vpn interface {}", vpnIf);
487             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier, vpnIf);
488         } catch (Exception ex) {
489             logger.error("Creation of vpninterface {} failed due to {}", infName, ex);
490         } finally {
491             if (isLockAcquired) {
492                 NeutronvpnUtils.unlock(lockManager, infName);
493             }
494         }
495     }
496
497     protected void deleteVpnInterface(Port port) {
498
499         if (port != null) {
500             boolean isLockAcquired = false;
501             String infName = port.getUuid().getValue();
502             InstanceIdentifier<VpnInterface> vpnIfIdentifier = NeutronvpnUtils.buildVpnInterfaceIdentifier(infName);
503
504             try {
505                 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
506                 logger.debug("Deleting vpn interface {}", infName);
507                 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier);
508             } catch (Exception ex) {
509                 logger.error("Deletion of vpninterface {} failed due to {}", infName, ex);
510             } finally {
511                 if (isLockAcquired) {
512                     NeutronvpnUtils.unlock(lockManager, infName);
513                 }
514             }
515         }
516     }
517
518     protected void updateVpnInterface(Uuid vpnId, Port port) {
519         if (vpnId == null || port == null) {
520             return;
521         }
522         boolean isLockAcquired = false;
523         String infName = port.getUuid().getValue();
524         InstanceIdentifier<VpnInterface> vpnIfIdentifier = NeutronvpnUtils.buildVpnInterfaceIdentifier(infName);
525         try {
526             Optional<VpnInterface> optionalVpnInterface = NeutronvpnUtils.read(broker, LogicalDatastoreType
527                     .CONFIGURATION, vpnIfIdentifier);
528             if (optionalVpnInterface.isPresent()) {
529                 VpnInterfaceBuilder vpnIfBuilder = new VpnInterfaceBuilder(optionalVpnInterface.get());
530                 VpnInterface vpnIf = vpnIfBuilder.setVpnInstanceName(vpnId.getValue()).build();
531                 isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
532                 logger.debug("Updating vpn interface {}", vpnIf);
533                 MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier, vpnIf);
534             } else {
535                 logger.error("VPN Interface {} not found", infName);
536             }
537         } catch (Exception ex) {
538             logger.error("Updation of vpninterface {} failed due to {}", infName, ex);
539         } finally {
540             if (isLockAcquired) {
541                 NeutronvpnUtils.unlock(lockManager, infName);
542             }
543         }
544     }
545
546     public void createL3Vpn(Uuid vpn, String name, Uuid tenant, List<String> rd, List<String> irt, List<String> ert,
547                             Uuid router, List<Uuid> networks) {
548
549         // Update VPN Instance node
550         updateVpnInstanceNode(vpn.getValue(), rd, irt, ert);
551
552         // Update local vpn-subnet DS
553         updateVpnMaps(vpn, name, router, tenant, networks);
554
555         if (router != null) {
556             associateRouterToVpn(vpn, router);
557         }
558         if (networks != null) {
559             associateNetworksToVpn(vpn, networks);
560         }
561     }
562
563     @Override
564     public Future<RpcResult<CreateL3VPNOutput>> createL3VPN(CreateL3VPNInput input) {
565
566         CreateL3VPNOutputBuilder opBuilder = new CreateL3VPNOutputBuilder();
567         SettableFuture<RpcResult<CreateL3VPNOutput>> result = SettableFuture.create();
568         List<RpcError> errorList = new ArrayList<>();
569         int failurecount = 0;
570         int warningcount = 0;
571
572         List<L3vpn> vpns = input.getL3vpn();
573         for (L3vpn vpn : vpns) {
574             RpcError error = null;
575             String msg;
576             if (vpn.getRouteDistinguisher() == null || vpn.getImportRT() == null || vpn.getExportRT() == null) {
577                 msg = String.format("Creation of L3VPN failed for VPN %s due to absence of RD/iRT/eRT input",
578                         vpn.getId().getValue());
579                 logger.warn(msg);
580                 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
581                 errorList.add(error);
582                 warningcount++;
583                 continue;
584             }
585             if (vpn.getRouteDistinguisher().size() > 1) {
586                 msg = String.format("Creation of L3VPN failed for VPN %s due to multiple RD input %s",
587                         vpn.getId().getValue(), vpn.getRouteDistinguisher());
588                 logger.warn(msg);
589                 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
590                 errorList.add(error);
591                 warningcount++;
592                 continue;
593             }
594             if (vpn.getRouterId() != null) {
595                 if (NeutronvpnUtils.getNeutronRouter(broker, vpn.getRouterId()) == null) {
596                     msg = String.format("Creation of L3VPN failed for VPN %s due to router not found %s",
597                             vpn.getId().getValue(), vpn.getRouterId().getValue());
598                     logger.warn(msg);
599                     error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
600                     errorList.add(error);
601                     warningcount++;
602                     continue;
603                 }
604                 Uuid vpnId = NeutronvpnUtils.getVpnForRouter(broker, vpn.getRouterId(), true);
605                 if (vpnId != null) {
606                     msg = String.format("Creation of L3VPN failed for VPN %s due to router %s already associated to " +
607                             "another VPN %s", vpn.getId().getValue(), vpn.getRouterId().getValue(), vpnId.getValue());
608                     logger.warn(msg);
609                     error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
610                     errorList.add(error);
611                     warningcount++;
612                     continue;
613                 }
614             }
615             if (vpn.getNetworkIds() != null) {
616                 for (Uuid nw : vpn.getNetworkIds()) {
617                     Network network = NeutronvpnUtils.getNeutronNetwork(broker, nw);
618                     Uuid vpnId = NeutronvpnUtils.getVpnForNetwork(broker, nw);
619                     if (network == null) {
620                         msg = String.format("Creation of L3VPN failed for VPN %s due to network not found %s",
621                                 vpn.getId().getValue(), nw.getValue());
622                         logger.warn(msg);
623                         error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
624                         errorList.add(error);
625                         warningcount++;
626                     } else if (vpnId != null) {
627                         msg = String.format("Creation of L3VPN failed for VPN %s due to network %s already associated" +
628                                 " to another VPN %s", vpn.getId().getValue(), nw.getValue(), vpnId.getValue());
629                         logger.warn(msg);
630                         error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
631                         errorList.add(error);
632                         warningcount++;
633                     }
634                 }
635                 if (error != null) {
636                     continue;
637                 }
638             }
639             try {
640                 createL3Vpn(vpn.getId(), vpn.getName(), vpn.getTenantId(), vpn.getRouteDistinguisher(),
641                         vpn.getImportRT(), vpn.getExportRT(), vpn.getRouterId(), vpn.getNetworkIds());
642             } catch (Exception ex) {
643                 msg = String.format("Creation of L3VPN failed for VPN %s", vpn.getId().getValue());
644                 logger.error(msg, ex);
645                 error = RpcResultBuilder.newError(ErrorType.APPLICATION, msg, ex.getMessage());
646                 errorList.add(error);
647                 failurecount++;
648             }
649         }
650         // if at least one succeeds; result is success
651         // if none succeeds; result is failure
652         if (failurecount + warningcount == vpns.size()) {
653             result.set(RpcResultBuilder.<CreateL3VPNOutput>failed().withRpcErrors(errorList).build());
654         } else {
655             List<String> errorResponseList = new ArrayList<>();
656             if (!errorList.isEmpty()) {
657                 for (RpcError rpcError : errorList) {
658                     String errorResponse = String.format("ErrorType: " + rpcError.getErrorType() + ", " + "ErrorTag: " +
659                             rpcError.getTag() + ", " + "ErrorMessage: " + rpcError.getMessage());
660                     errorResponseList.add(errorResponse);
661                 }
662             } else {
663                 errorResponseList.add("Operation successful with no errors");
664             }
665             opBuilder.setResponse(errorResponseList);
666             result.set(RpcResultBuilder.<CreateL3VPNOutput>success().withResult(opBuilder.build()).build());
667         }
668         return result;
669     }
670
671     @Override
672     public Future<RpcResult<GetL3VPNOutput>> getL3VPN(GetL3VPNInput input) {
673
674         GetL3VPNOutputBuilder opBuilder = new GetL3VPNOutputBuilder();
675         SettableFuture<RpcResult<GetL3VPNOutput>> result = SettableFuture.create();
676         Uuid inputVpnId = input.getId();
677         List<VpnInstance> vpns = new ArrayList<>();
678
679         try {
680             if (inputVpnId == null) {
681                 // get all vpns
682                 InstanceIdentifier<VpnInstances> vpnsIdentifier =
683                         InstanceIdentifier.builder(VpnInstances.class).build();
684                 Optional<VpnInstances> optionalVpns = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
685                         vpnsIdentifier);
686                 if (optionalVpns.isPresent() && optionalVpns.get().getVpnInstance() != null) {
687                     for (VpnInstance vpn : optionalVpns.get().getVpnInstance()) {
688                         // eliminating internal VPNs from getL3VPN output
689                         if (vpn.getIpv4Family().getRouteDistinguisher() != null) {
690                             vpns.add(vpn);
691                         }
692                     }
693                 } else {
694                     // No VPN present
695                     result.set(RpcResultBuilder.<GetL3VPNOutput>failed()
696                             .withWarning(ErrorType.PROTOCOL, "", "No VPN is present").build());
697                     return result;
698                 }
699             } else {
700                 String name = inputVpnId.getValue();
701                 InstanceIdentifier<VpnInstance> vpnIdentifier =
702                         InstanceIdentifier.builder(VpnInstances.class)
703                                 .child(VpnInstance.class, new VpnInstanceKey(name)).build();
704                 // read VpnInstance Info
705                 Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
706                         vpnIdentifier);
707                 if (optionalVpn.isPresent()) {
708                     vpns.add(optionalVpn.get());
709                 } else {
710                     String message = String.format("GetL3VPN failed because VPN %s is not present", name);
711                     logger.error(message);
712                     result.set(RpcResultBuilder.<GetL3VPNOutput>failed()
713                             .withWarning(ErrorType.PROTOCOL, "invalid-value", message).build());
714                 }
715             }
716             List<L3vpnInstances> l3vpnList = new ArrayList<>();
717             for (VpnInstance vpnInstance : vpns) {
718                 Uuid vpnId = new Uuid(vpnInstance.getVpnInstanceName());
719                 // create VpnMaps id
720                 InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class).child(VpnMap
721                         .class, new VpnMapKey(vpnId)).build();
722                 L3vpnInstancesBuilder l3vpn = new L3vpnInstancesBuilder();
723
724                 List<String> rd = Arrays.asList(vpnInstance.getIpv4Family().getRouteDistinguisher().split(","));
725                 List<VpnTarget> vpnTargetList = vpnInstance.getIpv4Family().getVpnTargets().getVpnTarget();
726
727                 List<String> ertList = new ArrayList<>();
728                 List<String> irtList = new ArrayList<>();
729
730                 for (VpnTarget vpnTarget : vpnTargetList) {
731                     if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.ExportExtcommunity) {
732                         ertList.add(vpnTarget.getVrfRTValue());
733                     }
734                     if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.ImportExtcommunity) {
735                         irtList.add(vpnTarget.getVrfRTValue());
736                     }
737                     if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.Both) {
738                         ertList.add(vpnTarget.getVrfRTValue());
739                         irtList.add(vpnTarget.getVrfRTValue());
740                     }
741                 }
742
743                 l3vpn.setId(vpnId).setRouteDistinguisher(rd).setImportRT(irtList).setExportRT(ertList);
744                 Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
745                         vpnMapIdentifier);
746                 if (optionalVpnMap.isPresent()) {
747                     VpnMap vpnMap = optionalVpnMap.get();
748                     l3vpn.setRouterId(vpnMap.getRouterId()).setNetworkIds(vpnMap.getNetworkIds())
749                             .setTenantId(vpnMap.getTenantId()).setName(vpnMap.getName());
750                 }
751                 l3vpnList.add(l3vpn.build());
752             }
753
754             opBuilder.setL3vpnInstances(l3vpnList);
755             result.set(RpcResultBuilder.<GetL3VPNOutput>success().withResult(opBuilder.build()).build());
756
757         } catch (Exception ex) {
758             String message = String.format("GetL3VPN failed due to %s", ex.getMessage());
759             logger.error(message, ex);
760             result.set(RpcResultBuilder.<GetL3VPNOutput>failed().withError(ErrorType.APPLICATION, message).build());
761         }
762         return result;
763     }
764
765     @Override
766     public Future<RpcResult<DeleteL3VPNOutput>> deleteL3VPN(DeleteL3VPNInput input) {
767
768         DeleteL3VPNOutputBuilder opBuilder = new DeleteL3VPNOutputBuilder();
769         SettableFuture<RpcResult<DeleteL3VPNOutput>> result = SettableFuture.create();
770         List<RpcError> errorList = new ArrayList<>();
771
772         int failurecount = 0;
773         int warningcount = 0;
774         List<Uuid> vpns = input.getId();
775         for (Uuid vpn : vpns) {
776             RpcError error;
777             String msg;
778             try {
779                 InstanceIdentifier<VpnInstance> vpnIdentifier =
780                         InstanceIdentifier.builder(VpnInstances.class)
781                                 .child(VpnInstance.class, new VpnInstanceKey(vpn.getValue())).build();
782                 Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
783                         vpnIdentifier);
784                 if (optionalVpn.isPresent()) {
785                     removeL3Vpn(vpn);
786                 } else {
787                     msg = String.format("VPN with vpnid: %s does not exist", vpn.getValue());
788                     logger.warn(msg);
789                     error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-value", msg);
790                     errorList.add(error);
791                     warningcount++;
792                 }
793             } catch (Exception ex) {
794                 msg = String.format("Deletion of L3VPN failed when deleting for uuid %s", vpn.getValue());
795                 logger.error(msg, ex);
796                 error = RpcResultBuilder.newError(ErrorType.APPLICATION, msg, ex.getMessage());
797                 errorList.add(error);
798                 failurecount++;
799             }
800         }
801         // if at least one succeeds; result is success
802         // if none succeeds; result is failure
803         if (failurecount + warningcount == vpns.size()) {
804             result.set(RpcResultBuilder.<DeleteL3VPNOutput>failed().withRpcErrors(errorList).build());
805         } else {
806             List<String> errorResponseList = new ArrayList<>();
807             if (!errorList.isEmpty()) {
808                 for (RpcError rpcError : errorList) {
809                     String errorResponse = String.format("ErrorType: " + rpcError.getErrorType() + ", " + "ErrorTag: " +
810                             rpcError.getTag() + ", " + "ErrorMessage: " + rpcError.getMessage());
811                     errorResponseList.add(errorResponse);
812                 }
813             } else {
814                 errorResponseList.add("Operation successful with no errors");
815             }
816             opBuilder.setResponse(errorResponseList);
817             result.set(RpcResultBuilder.<DeleteL3VPNOutput>success().withResult(opBuilder.build()).build());
818         }
819         return result;
820     }
821
822     protected void addSubnetToVpn(Uuid vpnId, Uuid subnet) {
823         logger.debug("Adding subnet {} to vpn {}", subnet.getValue(), vpnId.getValue());
824         Subnetmap sn = updateSubnetNode(subnet, null, null, null, null, vpnId, null);
825         boolean isLockAcquired = false;
826         String lockName = vpnId.getValue() + subnet.getValue();
827         String elanInstanceName = sn.getNetworkId().getValue();
828         InstanceIdentifier<ElanInstance>elanIdentifierId = InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
829         Optional<ElanInstance> elanInstance = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId);
830         long elanTag = elanInstance.get().getElanTag();
831         Uuid routerId = NeutronvpnUtils.getVpnMap(broker, vpnId).getRouterId();
832         if (vpnId.equals(routerId)) {
833             isExternalVpn = false;
834         } else {
835             isExternalVpn = true;
836         }
837         try {
838             isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
839             checkAndPublishSubnetAddNotification(subnet, sn.getSubnetIp(), vpnId.getValue(), isExternalVpn, elanTag);
840             logger.debug("Subnet added to Vpn notification sent");
841         }catch (Exception e){
842             logger.error("Subnet added to Vpn notification failed",e);
843         }finally {
844             if (isLockAcquired) {
845                 NeutronvpnUtils.unlock(lockManager, lockName);
846             }
847         }
848         // Check if there are ports on this subnet and add corresponding vpn-interfaces
849         List<Uuid> portList = sn.getPortList();
850         if (portList != null) {
851             for (Uuid port : sn.getPortList()) {
852                 logger.debug("adding vpn-interface for port {}", port.getValue());
853                 createVpnInterface(vpnId, NeutronvpnUtils.getNeutronPort(broker, port));
854             }
855         }
856     }
857
858     protected void updateVpnForSubnet(Uuid vpnId, Uuid subnet, boolean isBeingAssociated) {
859         logger.debug("Updating VPN {} for subnet {}", vpnId.getValue(), subnet.getValue());
860         Subnetmap sn = updateSubnetNode(subnet, null, null, null, null, vpnId, null);
861         boolean isLockAcquired = false;
862         String lockName = vpnId.getValue() + subnet.getValue();
863         String elanInstanceName = sn.getNetworkId().getValue();
864         InstanceIdentifier<ElanInstance>elanIdentifierId = InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
865         Optional<ElanInstance> elanInstance = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId);
866         long elanTag = elanInstance.get().getElanTag();
867         try {
868             isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
869             checkAndPublishSubnetUpdNotification(subnet, sn.getSubnetIp(), vpnId.getValue(), isBeingAssociated, elanTag);
870             logger.debug("Subnet updated in Vpn notification sent");
871         }catch (Exception e){
872             logger.error("Subnet updated in Vpn notification failed",e);
873         }finally {
874             if (isLockAcquired) {
875                 NeutronvpnUtils.unlock(lockManager, lockName);
876             }
877         }
878         // Check for ports on this subnet and update association of corresponding vpn-interfaces to external vpn
879         List<Uuid> portList = sn.getPortList();
880         if (portList != null) {
881             for (Uuid port : sn.getPortList()) {
882                 logger.debug("Updating vpn-interface for port {}", port.getValue());
883                 updateVpnInterface(vpnId, NeutronvpnUtils.getNeutronPort(broker, port));
884             }
885         }
886     }
887
888
889
890         // router-interfaces-map
891 //    list router-interfaces {
892 //        key router-id;
893 //        leaf router-id { type yang:uuid; }
894 //        list interfaces {
895 //            key interface-id;
896 //            leaf interface-id { type yang:uuid; }
897 //        }
898 //    }
899 ////}
900     InstanceIdentifier<RouterInterfaces> getRouterInterfacesId(Uuid routerId) {
901         return InstanceIdentifier.builder(RouterInterfacesMap.class)
902                 .child(RouterInterfaces.class, new RouterInterfacesKey(routerId)).build();
903     }
904     void addToNeutronRouterInterfacesMap(Uuid routerId, String interfaceName) {
905         InstanceIdentifier<RouterInterfaces> routerInterfacesId =  getRouterInterfacesId(routerId);
906         Optional<RouterInterfaces> optRouterInterfaces = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId);
907         Interfaces routerInterface = new InterfacesBuilder().setKey(new InterfacesKey(interfaceName)).setInterfaceId(interfaceName).build();
908         if(optRouterInterfaces.isPresent()) {
909             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId.child(Interfaces.class, new InterfacesKey(interfaceName)), routerInterface);
910         } else {
911             RouterInterfacesBuilder builder = new RouterInterfacesBuilder().setRouterId(routerId);
912             List<Interfaces> interfaces = new ArrayList<>();
913             interfaces.add(routerInterface);
914             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId, builder.setInterfaces(interfaces).build());
915         }
916     }
917     
918     void removeFromNeutronRouterInterfacesMap(Uuid routerId, String interfaceName) {
919         InstanceIdentifier<RouterInterfaces> routerInterfacesId =  getRouterInterfacesId(routerId);
920         Optional<RouterInterfaces> optRouterInterfaces = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId);
921         Interfaces routerInterface = new InterfacesBuilder().setKey(new InterfacesKey(interfaceName)).setInterfaceId(interfaceName).build();
922         if(optRouterInterfaces.isPresent()) {
923             RouterInterfaces routerInterfaces = optRouterInterfaces.get();
924             List<Interfaces> interfaces = routerInterfaces.getInterfaces();
925             if(interfaces != null && interfaces.remove(routerInterface)) {
926                 if(interfaces.isEmpty()) {
927                     MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId);
928                 } else {
929                     MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, routerInterfacesId.child(Interfaces.class, new InterfacesKey(interfaceName)));
930                 }
931             }
932         }
933     }
934
935     protected List<Adjacency> addAdjacencyforExtraRoute(List<Routes> routeList, boolean rtrUp, String vpnifname) {
936         List<Adjacency> adjList = new ArrayList<>();
937         for (Routes route : routeList) {
938             if (route != null && route.getNexthop() != null && route.getDestination() != null) {
939                 boolean isLockAcquired = false;
940                 String nextHop = String.valueOf(route.getNexthop().getValue());
941                 String destination = String.valueOf(route.getDestination().getValue());
942
943                 String infName = NeutronvpnUtils.getNeutronPortNamefromPortFixedIp(broker, nextHop);
944                 logger.trace("Adding extra route with nexthop {}, destination {}, infName {}", nextHop,
945                         destination, infName);
946                 Adjacency erAdj = new AdjacencyBuilder().setIpAddress(destination).setNextHopIp(nextHop).setKey
947                         (new AdjacencyKey(destination)).build();
948                 if (!rtrUp) {
949                     if (infName.equals(vpnifname)) {
950                         adjList.add(erAdj);
951                     }
952                     continue;
953                 }
954                 InstanceIdentifier<VpnInterface> vpnIfIdentifier = InstanceIdentifier.builder(VpnInterfaces.class).
955                         child(VpnInterface.class, new VpnInterfaceKey(infName)).build();
956                 try {
957                     Optional<VpnInterface> optionalVpnInterface = NeutronvpnUtils.read(broker, LogicalDatastoreType
958                             .CONFIGURATION, vpnIfIdentifier);
959                     if (optionalVpnInterface.isPresent()) {
960                         Adjacencies erAdjs = new AdjacenciesBuilder().setAdjacency(Arrays.asList(erAdj)).build();
961                         VpnInterface vpnIf = new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(infName))
962                                 .addAugmentation(Adjacencies.class, erAdjs).build();
963                         isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
964                         logger.debug("Adding extra route {}", route);
965                         MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier, vpnIf);
966                     } else {
967                         logger.error("VM adjacency for interface {} not present ; cannot add extra route adjacency",
968                                 infName);
969                     }
970                 } catch (Exception e) {
971                     logger.error("exception in adding extra route: {}" + e);
972                 } finally {
973                     if (isLockAcquired) {
974                         NeutronvpnUtils.unlock(lockManager, infName);
975                     }
976                 }
977             } else {
978                 logger.error("Incorrect input received for extra route. {}", route);
979             }
980         }
981         return adjList;
982     }
983
984     protected void removeAdjacencyforExtraRoute(List<Routes> routeList) {
985         for (Routes route : routeList) {
986             if (route != null && route.getNexthop() != null && route.getDestination() != null) {
987                 boolean isLockAcquired = false;
988                 String nextHop = String.valueOf(route.getNexthop().getValue());
989                 String destination = String.valueOf(route.getDestination().getValue());
990
991                 String infName = NeutronvpnUtils.getNeutronPortNamefromPortFixedIp(broker, nextHop);
992                 logger.trace("Removing extra route with nexthop {}, destination {}, infName {}", nextHop,
993                         destination, infName);
994                 InstanceIdentifier<Adjacency> adjacencyIdentifier = InstanceIdentifier.builder(VpnInterfaces.class).
995                         child(VpnInterface.class, new VpnInterfaceKey(infName)).augmentation(Adjacencies.class)
996                         .child(Adjacency.class, new AdjacencyKey(destination)).build();
997                 try {
998                     isLockAcquired = NeutronvpnUtils.lock(lockManager, infName);
999                     MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, adjacencyIdentifier);
1000                     logger.trace("extra route {} deleted successfully", route);
1001                 } catch (Exception e) {
1002                     logger.error("exception in deleting extra route: {}" + e);
1003                 } finally {
1004                     if (isLockAcquired) {
1005                         NeutronvpnUtils.unlock(lockManager, infName);
1006                     }
1007                 }
1008             } else {
1009                 logger.error("Incorrect input received for extra route. {}", route);
1010             }
1011         }
1012     }
1013
1014     protected void removeL3Vpn(Uuid id) {
1015         // read VPNMaps
1016         VpnMap vpnMap = NeutronvpnUtils.getVpnMap(broker, id);
1017         Uuid router = vpnMap.getRouterId();
1018         // dissociate router
1019         if (router != null) {
1020             dissociateRouterFromVpn(id, router);
1021         }
1022         // dissociate networks
1023         if (!id.equals(router)) {
1024             dissociateNetworksFromVpn(id, vpnMap.getNetworkIds());
1025         }
1026         // remove entire vpnMaps node
1027         deleteVpnMapsNode(id);
1028
1029         // remove vpn-instance
1030         deleteVpnInstance(id);
1031     }
1032
1033     protected void removeSubnetFromVpn(Uuid vpnId, Uuid subnet) {
1034         logger.debug("Removing subnet {} from vpn {}", subnet.getValue(), vpnId.getValue());
1035         Subnetmap sn = NeutronvpnUtils.getSubnetmap(broker, subnet);
1036         boolean isLockAcquired = false;
1037         String lockName = vpnId.getValue() + subnet.getValue();
1038         String elanInstanceName = sn.getNetworkId().getValue();
1039         InstanceIdentifier<ElanInstance>elanIdentifierId = InstanceIdentifier.builder(ElanInstances.class).child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build();
1040         Optional<ElanInstance> elanInstance = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, elanIdentifierId);
1041         long elanTag = elanInstance.get().getElanTag();
1042         Uuid routerId = NeutronvpnUtils.getVpnMap(broker, vpnId).getRouterId();
1043         if (vpnId.equals(routerId)) {
1044             isExternalVpn = false;
1045         } else {
1046             isExternalVpn = true;
1047         }
1048         try {
1049             isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
1050             checkAndPublishSubnetDelNotification(subnet, sn.getSubnetIp(), vpnId.getValue(), isExternalVpn, elanTag);
1051             logger.debug("Subnet removed from Vpn notification sent");
1052         }catch (Exception e){
1053             logger.error("Subnet removed from Vpn notification failed",e);
1054         }finally {
1055             if (isLockAcquired) {
1056                 NeutronvpnUtils.unlock(lockManager, lockName);
1057             }
1058         }
1059         if (sn != null) {
1060             // Check if there are ports on this subnet; remove corresponding vpn-interfaces
1061             List<Uuid> portList = sn.getPortList();
1062             if (portList != null) {
1063                 for (Uuid port : sn.getPortList()) {
1064                     logger.debug("removing vpn-interface for port {}", port.getValue());
1065                     deleteVpnInterface(NeutronvpnUtils.getNeutronPort(broker, port));
1066                     if (routerId != null) {
1067                         removeFromNeutronRouterInterfacesMap(routerId, port.getValue());
1068                     }
1069                 }
1070             }
1071             // update subnet-vpn association
1072             removeFromSubnetNode(subnet, null, null, vpnId, null);
1073         } else {
1074             logger.warn("Subnetmap for subnet {} not found", subnet.getValue());
1075         }
1076     }
1077
1078     protected void associateRouterToVpn(Uuid vpnId, Uuid routerId) {
1079         updateVpnMaps(vpnId, null, routerId, null, null);
1080         List<Uuid> routerSubnets = NeutronvpnUtils.getNeutronRouterSubnetIds(broker, routerId);
1081         if (!vpnId.equals(routerId)) {
1082             logger.debug("Updating association of subnets to external vpn {}", vpnId.getValue());
1083             if (routerSubnets != null) {
1084                 for (Uuid subnetId : routerSubnets) {
1085                     updateVpnForSubnet(vpnId, subnetId,true);
1086                 }
1087             }
1088         } else {
1089             logger.debug("Adding subnets to internal vpn {}", vpnId.getValue());
1090             for (Uuid subnet : routerSubnets) {
1091                 addSubnetToVpn(vpnId, subnet);
1092             }
1093         }
1094     }
1095
1096     protected void dissociateRouterFromVpn(Uuid vpnId, Uuid routerId) {
1097
1098         List<Uuid> routerSubnets = NeutronvpnUtils.getNeutronRouterSubnetIds(broker, routerId);
1099         if (routerSubnets != null) {
1100             for (Uuid subnetId : routerSubnets) {
1101                 logger.debug("Updating association of subnets to internal vpn {}", routerId.getValue());
1102                 updateVpnForSubnet(routerId, subnetId,false);
1103             }
1104         }
1105         clearFromVpnMaps(vpnId, routerId, null);
1106     }
1107
1108     protected List<String> associateNetworksToVpn(Uuid vpn, List<Uuid> networks) {
1109         List<String> failed = new ArrayList<>();
1110         if (!networks.isEmpty()) {
1111             // store in Data Base
1112             updateVpnMaps(vpn, null, null, null, networks);
1113             // process corresponding subnets for VPN
1114             for (Uuid nw : networks) {
1115                 Network net = NeutronvpnUtils.getNeutronNetwork(broker, nw);
1116                 if (net == null) {
1117                     failed.add(nw.getValue());
1118                 } else {
1119                     List<Uuid> networkSubnets = NeutronvpnUtils.getSubnetIdsFromNetworkId(broker, nw);
1120                     logger.debug("Adding network subnets...");
1121                     if (networkSubnets != null) {
1122                         for (Uuid subnet : networkSubnets) {
1123                             addSubnetToVpn(vpn, subnet);
1124                         }
1125                     }
1126                     if (net.getAugmentation(NetworkL3Extension.class).isExternal()) {
1127                         nvpnNatManager.addExternalNetworkToVpn(net, vpn);
1128                     }
1129                 }
1130             }
1131         }
1132         return failed;
1133     }
1134
1135     protected List<String> dissociateNetworksFromVpn(Uuid vpn, List<Uuid> networks) {
1136         List<String> failed = new ArrayList<>();
1137         if (networks != null && !networks.isEmpty()) {
1138             // store in Data Base
1139             clearFromVpnMaps(vpn, null, networks);
1140             // process corresponding subnets for VPN
1141             for (Uuid nw : networks) {
1142                 Network net = NeutronvpnUtils.getNeutronNetwork(broker, nw);
1143                 if (net == null) {
1144                     failed.add(nw.getValue());
1145                 } else {
1146                     List<Uuid> networkSubnets = NeutronvpnUtils.getSubnetIdsFromNetworkId(broker, nw);
1147                     logger.debug("Removing network subnets...");
1148                     if (networkSubnets != null) {
1149                         for (Uuid subnet : networkSubnets) {
1150                             removeSubnetFromVpn(vpn, subnet);
1151                         }
1152                     }
1153                     if (net.getAugmentation(NetworkL3Extension.class).isExternal()) {
1154                         nvpnNatManager.removeExternalNetworkFromVpn(net);
1155                     }
1156                 }
1157             }
1158         }
1159         return failed;
1160     }
1161
1162     @Override
1163     public Future<RpcResult<AssociateNetworksOutput>> associateNetworks(AssociateNetworksInput input) {
1164
1165         AssociateNetworksOutputBuilder opBuilder = new AssociateNetworksOutputBuilder();
1166         SettableFuture<RpcResult<AssociateNetworksOutput>> result = SettableFuture.create();
1167         logger.debug("associateNetworks {}", input);
1168         StringBuilder returnMsg = new StringBuilder();
1169         Uuid vpnId = input.getVpnId();
1170
1171         try {
1172             if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
1173                 List<Uuid> netIds = input.getNetworkId();
1174                 if (netIds != null && !netIds.isEmpty()) {
1175                     List<String> failed = associateNetworksToVpn(vpnId, netIds);
1176                     if (!failed.isEmpty()) {
1177                         returnMsg.append("network(s) not found : ").append(failed);
1178                     }
1179                 }
1180             } else {
1181                 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1182             }
1183             if (returnMsg.length() != 0) {
1184                 String message = String.format("associate Networks to vpn %s failed due to %s", vpnId.getValue(),
1185                         returnMsg);
1186                 logger.error(message);
1187                 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
1188                         message);
1189                 opBuilder.setResponse(errorResponse);
1190                 result.set(RpcResultBuilder.<AssociateNetworksOutput>success().withResult(opBuilder.build()).build());
1191             } else {
1192                 result.set(RpcResultBuilder.<AssociateNetworksOutput>success().build());
1193             }
1194         } catch (Exception ex) {
1195             String message = String.format("associate Networks to vpn %s failed due to %s", input.getVpnId().getValue(),
1196                     ex.getMessage());
1197             logger.error(message, ex);
1198             result.set(RpcResultBuilder.<AssociateNetworksOutput>failed().withError(ErrorType.APPLICATION, message)
1199                     .build());
1200         }
1201         logger.debug("associateNetworks returns..");
1202         return result;
1203     }
1204
1205     @Override
1206     public Future<RpcResult<Void>> associateRouter(AssociateRouterInput input) {
1207
1208         SettableFuture<RpcResult<Void>> result = SettableFuture.create();
1209         logger.debug("associateRouter {}", input);
1210         StringBuilder returnMsg = new StringBuilder();
1211         Uuid vpnId = input.getVpnId();
1212         Uuid routerId = input.getRouterId();
1213         try {
1214             if (routerId != null && vpnId != null) {
1215                 Router rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
1216                 VpnMap vpnMap = NeutronvpnUtils.getVpnMap(broker, vpnId);
1217                 if (rtr != null && vpnMap != null) {
1218                     if (vpnMap.getRouterId() != null) {
1219                         returnMsg.append("vpn ").append(vpnId.getValue()).append(" already associated to router ")
1220                                 .append(vpnMap.getRouterId().getValue());
1221                     } else {
1222                         associateRouterToVpn(vpnId, routerId);
1223                     }
1224                 } else {
1225                     returnMsg.append("router not found : ").append(routerId.getValue());
1226                 }
1227             } else {
1228                 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1229             }
1230             if (returnMsg.length() != 0) {
1231                 String message = String.format("associate router to vpn %s failed due to %s", routerId.getValue(),
1232                         returnMsg);
1233                 logger.error(message);
1234                 result.set(RpcResultBuilder.<Void>failed().withWarning(ErrorType.PROTOCOL, "invalid-value", message)
1235                         .build());
1236             } else {
1237                 result.set(RpcResultBuilder.<Void>success().build());
1238             }
1239         } catch (Exception ex) {
1240             String message = String.format("associate router %s to vpn %s failed due to %s", routerId.getValue(),
1241                     vpnId.getValue(), ex.getMessage());
1242             logger.error(message, ex);
1243             result.set(RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, message).build());
1244         }
1245         logger.debug("associateRouter returns..");
1246         return result;
1247     }
1248
1249     @Override
1250     public Future<RpcResult<DissociateNetworksOutput>> dissociateNetworks(DissociateNetworksInput input) {
1251
1252         DissociateNetworksOutputBuilder opBuilder = new DissociateNetworksOutputBuilder();
1253         SettableFuture<RpcResult<DissociateNetworksOutput>> result = SettableFuture.create();
1254
1255         logger.debug("dissociateNetworks {}", input);
1256         StringBuilder returnMsg = new StringBuilder();
1257         Uuid vpnId = input.getVpnId();
1258
1259         try {
1260             if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
1261                 List<Uuid> netIds = input.getNetworkId();
1262                 if (netIds != null && !netIds.isEmpty()) {
1263                     List<String> failed = dissociateNetworksFromVpn(vpnId, netIds);
1264                     if (!failed.isEmpty()) {
1265                         returnMsg.append("netowrk(s) not found : ").append(failed);
1266                     }
1267                 }
1268             } else {
1269                 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1270             }
1271             if (returnMsg.length() != 0) {
1272                 String message = String.format("dissociate Networks to vpn %s failed due to %s", vpnId.getValue(),
1273                         returnMsg);
1274                 logger.error(message);
1275                 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
1276                         message);
1277                 opBuilder.setResponse(errorResponse);
1278                 result.set(RpcResultBuilder.<DissociateNetworksOutput>success().withResult(opBuilder.build()).build());
1279             } else {
1280                 result.set(RpcResultBuilder.<DissociateNetworksOutput>success().build());
1281             }
1282         } catch (Exception ex) {
1283             String message = String.format("dissociate Networks to vpn %s failed due to %s", input.getVpnId().
1284                     getValue(), ex.getMessage());
1285             logger.error(message, ex);
1286             result.set(RpcResultBuilder.<DissociateNetworksOutput>failed().withError(ErrorType.APPLICATION, message)
1287                     .build());
1288         }
1289         logger.debug("dissociateNetworks returns..");
1290         return result;
1291     }
1292
1293     @Override
1294     public Future<RpcResult<Void>> dissociateRouter(DissociateRouterInput input) {
1295
1296         SettableFuture<RpcResult<Void>> result = SettableFuture.create();
1297
1298         logger.debug("dissociateRouter {}", input);
1299         StringBuilder returnMsg = new StringBuilder();
1300         Uuid vpnId = input.getVpnId();
1301         Uuid routerId = input.getRouterId();
1302         try {
1303             if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
1304                 if (routerId != null) {
1305                     Router rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
1306                     if (rtr != null) {
1307                         dissociateRouterFromVpn(vpnId, routerId);
1308                     } else {
1309                         returnMsg.append("router not found : ").append(routerId.getValue());
1310                     }
1311                 }
1312             } else {
1313                 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1314             }
1315             if (returnMsg.length() != 0) {
1316                 String message = String.format("dissociate router %s to vpn %s failed due to %s", routerId.getValue(),
1317                         vpnId.getValue(), returnMsg);
1318                 logger.error(message);
1319                 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
1320                         message);
1321                 result.set(RpcResultBuilder.<Void>failed().withWarning(ErrorType.PROTOCOL, "invalid-value", message)
1322                         .build());
1323             } else {
1324                 result.set(RpcResultBuilder.<Void>success().build());
1325             }
1326         } catch (Exception ex) {
1327             String message = String.format("disssociate router %s to vpn %s failed due to %s", routerId.getValue(),
1328                     vpnId.getValue(), ex.getMessage());
1329             logger.error(message, ex);
1330             result.set(RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, message).build());
1331         }
1332         logger.debug("dissociateRouter returns..");
1333
1334         return result;
1335     }
1336
1337     @Override
1338     public Future<RpcResult<GetFixedIPsForNeutronPortOutput>> getFixedIPsForNeutronPort(GetFixedIPsForNeutronPortInput
1339                                                                                                 input) {
1340         GetFixedIPsForNeutronPortOutputBuilder opBuilder = new GetFixedIPsForNeutronPortOutputBuilder();
1341         SettableFuture<RpcResult<GetFixedIPsForNeutronPortOutput>> result = SettableFuture.create();
1342         Uuid portId = input.getPortId();
1343         StringBuilder returnMsg = new StringBuilder();
1344         try {
1345             List<String> fixedIPList = new ArrayList<>();
1346             Port port = NeutronvpnUtils.getNeutronPort(broker, portId);
1347             if (port != null) {
1348                 List<FixedIps> fixedIPs = port.getFixedIps();
1349                 for (FixedIps ip : fixedIPs) {
1350                     fixedIPList.add(ip.getIpAddress().getIpv4Address().getValue());
1351                 }
1352             } else {
1353                 returnMsg.append("neutron port: ").append(portId.getValue()).append(" not found");
1354             }
1355             if (returnMsg.length() != 0) {
1356                 String message = String.format("Retrieval of FixedIPList for neutron port failed due to %s", returnMsg);
1357                 logger.error(message);
1358                 result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>failed().withWarning(ErrorType.PROTOCOL,
1359                         "invalid-value", message).build());
1360             } else {
1361                 opBuilder.setFixedIPs(fixedIPList);
1362                 result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>success().withResult(opBuilder.build())
1363                         .build());
1364                 result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>success().build());
1365             }
1366         } catch (Exception ex) {
1367             String message = String.format("Retrieval of FixedIPList for neutron port %s failed due to %s", portId
1368                     .getValue(), ex.getMessage());
1369             logger.error(message, ex);
1370             result.set(RpcResultBuilder.<GetFixedIPsForNeutronPortOutput>failed().withError(ErrorType.APPLICATION,
1371                     message).build());
1372         }
1373         return result;
1374     }
1375
1376     protected void handleNeutronRouterDeleted(Uuid routerId, List<Uuid> routerSubnetIds) {
1377         // check if the router is associated to some VPN
1378         Uuid vpnId = NeutronvpnUtils.getVpnForRouter(broker, routerId, true);
1379         if (vpnId != null) {
1380             // remove existing external vpn interfaces
1381             for (Uuid subnetId : routerSubnetIds) {
1382                 removeSubnetFromVpn(vpnId, subnetId);
1383             }
1384             clearFromVpnMaps(vpnId, routerId, null);
1385         } else {
1386             // remove existing internal vpn interfaces
1387             for (Uuid subnetId : routerSubnetIds) {
1388                 removeSubnetFromVpn(routerId, subnetId);
1389             }
1390         }
1391         // delete entire vpnMaps node for internal VPN
1392         deleteVpnMapsNode(routerId);
1393
1394         // delete vpn-instance for internal VPN
1395         deleteVpnInstance(routerId);
1396     }
1397
1398     protected Subnet getNeutronSubnet(Uuid subnetId){
1399         return NeutronvpnUtils.getNeutronSubnet(broker, subnetId);
1400     }
1401
1402     protected IpAddress getNeutronSubnetGateway(Uuid subnetId) {
1403         Subnet sn = NeutronvpnUtils.getNeutronSubnet(broker, subnetId);
1404         if (null != sn) {
1405             return sn.getGatewayIp();
1406         }
1407         return null;
1408     }
1409
1410     protected Port getNeutronPort(String name) {
1411         return NeutronvpnUtils.getNeutronPort(broker, new Uuid(name));
1412     }
1413
1414     protected Port getNeutronPort(Uuid portId) {
1415         return NeutronvpnUtils.getNeutronPort(broker, portId);
1416     }
1417
1418     protected List<Uuid> getSubnetsforVpn(Uuid vpnid) {
1419         List<Uuid> subnets = new ArrayList<>();
1420         //read subnetmaps
1421         InstanceIdentifier<Subnetmaps> subnetmapsid = InstanceIdentifier.builder(Subnetmaps.class).build();
1422         Optional<Subnetmaps> subnetmaps = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
1423                 subnetmapsid);
1424         if (subnetmaps.isPresent() && subnetmaps.get().getSubnetmap() != null) {
1425             List<Subnetmap> subnetMapList = subnetmaps.get().getSubnetmap();
1426             for (Subnetmap subnetMap : subnetMapList) {
1427                 if (subnetMap.getVpnId() != null && subnetMap.getVpnId().equals(vpnid)) {
1428                     subnets.add(subnetMap.getId());
1429                 }
1430             }
1431         }
1432         return subnets;
1433     }
1434
1435     public List<String> showNeutronPortsCLI() {
1436         List<String> result = new ArrayList<>();
1437         result.add(String.format(" %-34s  %-22s  %-22s  %-6s ", "PortName", "Mac Address", "IP Address",
1438                 "Prefix Length"));
1439         result.add("---------------------------------------------------------------------------------------");
1440         InstanceIdentifier<Ports> portidentifier = InstanceIdentifier.create(Neutron.class).child(Ports.class);
1441         try {
1442             Optional<Ports> ports = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, portidentifier);
1443             if (ports.isPresent() && ports.get().getPort() != null) {
1444                 List<Port> portList = ports.get().getPort();
1445                 for (Port port : portList) {
1446                     result.add(String.format(" %-34s  %-22s  %-22s  %-6s ", port.getUuid().getValue(), port
1447                             .getMacAddress(), port.getFixedIps().get(0).getIpAddress().getIpv4Address().getValue(),
1448                             NeutronvpnUtils.getIPPrefixFromPort(broker, port)));
1449                 }
1450             }
1451         } catch (Exception e) {
1452             logger.error("Failed to retrieve neutronPorts info : ", e);
1453             System.out.println("Failed to retrieve neutronPorts info : " + e.getMessage());
1454         }
1455         return result;
1456     }
1457
1458     public List<String> showVpnConfigCLI(Uuid vpnuuid) {
1459         List<String> result = new ArrayList<>();
1460         if (vpnuuid == null) {
1461             System.out.println("");
1462             System.out.println("Displaying VPN config for all VPNs");
1463             System.out.println("To display VPN config for a particular VPN, use the following syntax");
1464             System.out.println(getshowVpnConfigCLIHelp());
1465         }
1466         try {
1467             RpcResult<GetL3VPNOutput> rpcResult = getL3VPN(new GetL3VPNInputBuilder().setId(vpnuuid).build()).get();
1468             if (rpcResult.isSuccessful()) {
1469                 result.add("");
1470                 result.add(String.format(" %-37s %-37s %-7s ", "VPN ID", "Tenant ID", "RD"));
1471                 result.add("");
1472                 result.add(String.format(" %-80s ", "Import-RTs"));
1473                 result.add("");
1474                 result.add(String.format(" %-80s ", "Export-RTs"));
1475                 result.add("");
1476                 result.add(String.format(" %-76s ", "Subnet IDs"));
1477                 result.add("");
1478                 result.add("------------------------------------------------------------------------------------");
1479                 result.add("");
1480                 List<L3vpnInstances> VpnList = rpcResult.getResult().getL3vpnInstances();
1481                 for (L3vpnInstance Vpn : VpnList) {
1482                     String tenantId = Vpn.getTenantId() != null ? Vpn.getTenantId().getValue() : "\"                 " +
1483                             "                  \"";
1484                     result.add(String.format(" %-37s %-37s %-7s ", Vpn.getId().getValue(), tenantId, Vpn
1485                             .getRouteDistinguisher()));
1486                     result.add("");
1487                     result.add(String.format(" %-80s ", Vpn.getImportRT()));
1488                     result.add("");
1489                     result.add(String.format(" %-80s ", Vpn.getExportRT()));
1490                     result.add("");
1491
1492                     Uuid vpnid = Vpn.getId();
1493                     List<Uuid> subnetList = getSubnetsforVpn(vpnid);
1494                     if (!subnetList.isEmpty()) {
1495                         for (Uuid subnetuuid : subnetList) {
1496                             result.add(String.format(" %-76s ", subnetuuid.getValue()));
1497                         }
1498                     } else {
1499                         result.add(String.format(" %-76s ", "\"                                    \""));
1500                     }
1501                     result.add("");
1502                     result.add("----------------------------------------");
1503                     result.add("");
1504                 }
1505             } else {
1506                 String errortag = rpcResult.getErrors().iterator().next().getTag();
1507                 if (errortag == "") {
1508                     System.out.println("");
1509                     System.out.println("No VPN has been configured yet");
1510                 } else if (errortag == "invalid-value") {
1511                     System.out.println("");
1512                     System.out.println("VPN " + vpnuuid.getValue() + " is not present");
1513                 } else {
1514                     System.out.println("error getting VPN info : " + rpcResult.getErrors());
1515                     System.out.println(getshowVpnConfigCLIHelp());
1516                 }
1517             }
1518         } catch (InterruptedException | ExecutionException e) {
1519             logger.error("error getting VPN info : ", e);
1520             System.out.println("error getting VPN info : " + e.getMessage());
1521         }
1522         return result;
1523     }
1524
1525     private String getshowVpnConfigCLIHelp() {
1526         StringBuilder help = new StringBuilder("Usage:");
1527         help.append("display vpn-config [-vid/--vpnid <id>]");
1528         return help.toString();
1529     }
1530
1531     private void checkAndPublishSubnetAddNotification(Uuid subnetId, String subnetIp, String vpnName, Boolean isExternalvpn, Long elanTag)throws InterruptedException{
1532         SubnetAddedToVpnBuilder builder = new SubnetAddedToVpnBuilder();
1533
1534         logger.info("publish notification called");
1535
1536         builder.setSubnetId(subnetId);
1537         builder.setSubnetIp(subnetIp);
1538         builder.setVpnName(vpnName);
1539         builder.setExternalVpn(isExternalvpn);
1540         builder.setElanTag(elanTag);
1541
1542         notificationPublishService.putNotification(builder.build());
1543     }
1544
1545     private void checkAndPublishSubnetDelNotification(Uuid subnetId, String subnetIp, String vpnName, Boolean isExternalvpn, Long elanTag)throws InterruptedException{
1546         SubnetDeletedFromVpnBuilder builder = new SubnetDeletedFromVpnBuilder();
1547
1548         logger.info("publish notification called");
1549
1550         builder.setSubnetId(subnetId);
1551         builder.setSubnetIp(subnetIp);
1552         builder.setVpnName(vpnName);
1553         builder.setExternalVpn(isExternalvpn);
1554         builder.setElanTag(elanTag);
1555
1556         notificationPublishService.putNotification(builder.build());
1557     }
1558
1559     private void checkAndPublishSubnetUpdNotification(Uuid subnetId, String subnetIp, String vpnName, Boolean isExternalvpn, Long elanTag)throws InterruptedException{
1560         SubnetUpdatedInVpnBuilder builder = new SubnetUpdatedInVpnBuilder();
1561
1562         logger.info("publish notification called");
1563
1564         builder.setSubnetId(subnetId);
1565         builder.setSubnetIp(subnetIp);
1566         builder.setVpnName(vpnName);
1567         builder.setExternalVpn(isExternalvpn);
1568         builder.setElanTag(elanTag);
1569
1570         notificationPublishService.putNotification(builder.build());
1571     }
1572
1573 }