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