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