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