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