a94101d0fb0328d15fb59cb7794d6eb09319c486
[vpnservice.git] / neutronvpn / neutronvpn-impl / src / main / java / org / opendaylight / vpnservice / neutronvpn / NeutronvpnManager.java
1 /*
2  * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.vpnservice.neutronvpn;
9
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.SettableFuture;
12
13 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
14 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
15 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil;
16 import org.opendaylight.vpnservice.mdsalutil.interfaces.IMdsalApiManager;
17 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInstances;
18 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInterfaces;
19 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.VpnTargets;
20 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.VpnTargetsBuilder;
21 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.vpntargets.VpnTarget;
22 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.vpntargets
23         .VpnTargetBuilder;
24 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.af.config.vpntargets.VpnTargetKey;
25 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstance;
26 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceBuilder;
27 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceKey;
28 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.vpn.instance
29         .Ipv4FamilyBuilder;
30 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterface;
31 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterfaceBuilder;
32 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.interfaces.VpnInterfaceKey;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.Adjacencies;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.AdjacenciesBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.adjacency.list.Adjacency;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.adjacency.list.AdjacencyBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.adjacency.list.AdjacencyKey;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.PortKey;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.SubnetKey;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.lockmanager.rev150819.LockManagerService;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.AssociateNetworksInput;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.AssociateNetworksOutput;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.AssociateNetworksOutputBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.AssociateRouterInput;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.CreateL3VPNInput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.CreateL3VPNOutput;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.CreateL3VPNOutputBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.DeleteL3VPNInput;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.DeleteL3VPNOutput;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.DeleteL3VPNOutputBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.DissociateNetworksInput;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.DissociateNetworksOutput;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.DissociateNetworksOutputBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.DissociateRouterInput;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.GetL3VPNInput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.GetL3VPNInputBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.GetL3VPNOutput;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.GetL3VPNOutputBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.L3vpnInstance;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.NeutronvpnService;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.Subnetmaps;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.VpnMaps;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.createl3vpn.input.L3vpn;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.getl3vpn.output.L3vpnInstances;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.getl3vpn.output
75         .L3vpnInstancesBuilder;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.subnetmaps.Subnetmap;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.subnetmaps.SubnetmapBuilder;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.subnetmaps.SubnetmapKey;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.vpnmaps.VpnMap;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.vpnmaps.VpnMapBuilder;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.neutronvpn.rev150602.vpnmaps.VpnMapKey;
82 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
83 import org.opendaylight.yangtools.yang.common.RpcError;
84 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
85 import org.opendaylight.yangtools.yang.common.RpcResult;
86 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
89
90 import java.util.ArrayList;
91 import java.util.Arrays;
92 import java.util.List;
93 import java.util.concurrent.ExecutionException;
94 import java.util.concurrent.Future;
95
96 public class NeutronvpnManager implements NeutronvpnService, AutoCloseable {
97
98     private static final Logger logger = LoggerFactory.getLogger(NeutronvpnManager.class);
99     private final DataBroker broker;
100     private LockManagerService lockManager;
101     IMdsalApiManager mdsalUtil;
102
103     /**
104      * @param db           - dataBroker reference
105      * @param mdsalManager - MDSAL Util API access
106      */
107     public NeutronvpnManager(final DataBroker db, IMdsalApiManager mdsalManager) {
108         broker = db;
109         mdsalUtil = mdsalManager;
110     }
111
112     public void setLockManager(LockManagerService lockManager) {
113         this.lockManager = lockManager;
114     }
115
116     @Override
117     public void close() throws Exception {
118         logger.info("Neutron VPN Manager Closed");
119     }
120
121     protected Subnetmap updateSubnetNode(Uuid subnetId, Uuid tenantId, Uuid networkId, Uuid routerId, Uuid vpnId,
122                                          Uuid portId) {
123
124         try {
125             SubnetmapBuilder builder = null;
126
127             InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class).
128                     child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
129             Optional<Subnetmap> sn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, id);
130             logger.debug("updating Subnet :read: ");
131             if (sn.isPresent()) {
132                 builder = new SubnetmapBuilder(sn.get());
133                 logger.debug("updating Subnet :existing: ");
134             } else {
135                 builder = new SubnetmapBuilder().setKey(new SubnetmapKey(subnetId)).setId(subnetId);
136                 logger.debug("updating Subnet :new: ");
137             }
138
139             if (routerId != null) {
140                 builder.setRouterId(routerId);
141             }
142             if (networkId != null) {
143                 builder.setNetworkId(networkId);
144             }
145             if (vpnId != null) {
146                 builder.setVpnId(vpnId);
147             }
148             if (tenantId != null) {
149                 builder.setTenantId(tenantId);
150             }
151
152             if (portId != null) {
153                 List<Uuid> portList = builder.getPortList();
154                 if (portList == null) {
155                     portList = new ArrayList<Uuid>();
156                 }
157                 portList.add(portId);
158                 builder.setPortList(portList);
159             }
160
161             Subnetmap subnetmap = builder.build();
162             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, subnetmap);
163             logger.debug("Created/Updated subnetmap node: {} ", subnetId.getValue());
164
165             return subnetmap;
166         } catch (Exception e) {
167             logger.error("Update local subnetmap failed for node: {} {} {} {} {} {} ",
168                     subnetId.getValue(), tenantId.getValue(), networkId.getValue(), routerId.getValue(), vpnId
169                             .getValue(), portId.getValue());
170             throw new RuntimeException(e);
171         }
172
173     }
174
175     protected Subnetmap removeFromSubnetNode(Uuid subnetId, Uuid networkId, Uuid routerId, Uuid vpnId, Uuid portId) {
176         Subnetmap subnetmap = null;
177         try {
178             InstanceIdentifier<Subnetmap> id = InstanceIdentifier.builder(Subnetmaps.class).
179                     child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
180             Optional<Subnetmap> sn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, id);
181
182             if (sn.isPresent()) {
183                 SubnetmapBuilder builder = new SubnetmapBuilder(sn.get());
184
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                 logger.debug("Removing from existing subnetmap node: {} ", subnetId.getValue());
202                 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, subnetmap);
203             } else {
204                 logger.warn("remove from non-existing subnetmap node: {} ", subnetId.getValue());
205             }
206         } catch (Exception e) {
207             logger.error("Remove from subnetmap failed for node: {} {} {} {} {} {} ", subnetId.getValue(), networkId
208                     .getValue(), routerId.getValue(), vpnId.getValue(), portId.getValue());
209             throw new RuntimeException(e);
210         }
211
212         return subnetmap;
213     }
214
215     private void updateVpnInstanceNode(String name, List<String> rd, List<String> irt, List<String> ert) {
216
217         try {
218             VpnInstanceBuilder builder = null;
219             List<VpnTarget> vpnTargetList = new ArrayList<VpnTarget>();
220             InstanceIdentifier<VpnInstance> vpnIdentifier = InstanceIdentifier.builder(VpnInstances.class).
221                     child(VpnInstance.class, new VpnInstanceKey(name)).build();
222             Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
223                     vpnIdentifier);
224             logger.debug("Creating/Updating a new vpn-instance node: {} ", name);
225             if (optionalVpn.isPresent()) {
226                 builder = new VpnInstanceBuilder(optionalVpn.get());
227                 logger.debug("updating existing vpninstance node");
228             } else {
229                 builder = new VpnInstanceBuilder().setKey(new VpnInstanceKey(name)).setVpnInstanceName(name);
230             }
231
232             if (irt != null && !irt.isEmpty()) {
233                 if (ert != null && !ert.isEmpty()) {
234                     List<String> commonRT = new ArrayList<String>(irt);
235                     commonRT.retainAll(ert);
236
237                     for (String common : commonRT) {
238                         irt.remove(common);
239                         ert.remove(common);
240                         VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(common)).setVrfRTValue
241                                 (common).setVrfRTType(VpnTarget.VrfRTType.Both).build();
242                         vpnTargetList.add(vpnTarget);
243                     }
244                 }
245                 for (String importRT : irt) {
246                     VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(importRT)).setVrfRTValue
247                             (importRT).setVrfRTType(VpnTarget.VrfRTType.ImportExtcommunity).build();
248                     vpnTargetList.add(vpnTarget);
249                 }
250             }
251
252             if (ert != null && !ert.isEmpty()) {
253                 for (String exportRT : ert) {
254                     VpnTarget vpnTarget = new VpnTargetBuilder().setKey(new VpnTargetKey(exportRT)).setVrfRTValue
255                             (exportRT).setVrfRTType(VpnTarget.VrfRTType.ExportExtcommunity).build();
256                     vpnTargetList.add(vpnTarget);
257                 }
258             }
259
260             VpnTargets vpnTargets = new VpnTargetsBuilder().setVpnTarget(vpnTargetList).build();
261
262             Ipv4FamilyBuilder ipv4vpnBuilder = new Ipv4FamilyBuilder().setVpnTargets(vpnTargets);
263
264             if (rd != null && !rd.isEmpty()) {
265                 ipv4vpnBuilder.setRouteDistinguisher(rd.get(0));
266             }
267
268             VpnInstance newVpn = builder.setIpv4Family(ipv4vpnBuilder.build()).build();
269             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnIdentifier, newVpn);
270             logger.debug("Created/Updated vpn-instance for {} ", name);
271         } catch (Exception e) {
272             logger.error("Update VPN Instance node failed for node: {} {} {} {}", name, rd, irt, ert);
273             throw new RuntimeException(e);
274         }
275     }
276
277     private void deleteVpnMapsNode(Uuid vpnid) {
278         InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
279                 .child(VpnMap.class, new VpnMapKey(vpnid)).build();
280         logger.debug("removing vpnMaps node: {} ", vpnid.getValue());
281         MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
282     }
283
284     private void updateVpnMaps(Uuid vpnId, String name, Uuid router, Uuid tenantId, List<Uuid> networks) {
285         VpnMapBuilder builder;
286         InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
287                 .child(VpnMap.class, new VpnMapKey(vpnId)).build();
288         Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
289                 vpnMapIdentifier);
290         if (optionalVpnMap.isPresent()) {
291             builder = new VpnMapBuilder(optionalVpnMap.get());
292         } else {
293             builder = new VpnMapBuilder().setKey(new VpnMapKey(vpnId)).setVpnId(vpnId);
294         }
295
296         if (name != null) {
297             builder.setName(name);
298         }
299         if (tenantId != null) {
300             builder.setTenantId(tenantId);
301         }
302         if (router != null) {
303             builder.setRouterId(router);
304         }
305         if (networks != null) {
306             List<Uuid> nwList = builder.getNetworkIds();
307             if (nwList == null) {
308                 nwList = new ArrayList<Uuid>();
309             }
310             nwList.addAll(networks);
311             builder.setNetworkIds(nwList);
312         }
313
314         logger.debug("Creating/Updating vpnMaps node: {} ", vpnId.getValue());
315         MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier, builder.build());
316         logger.debug("VPNMaps DS updated for VPN {} ", vpnId.getValue());
317     }
318
319     private void clearFromVpnMaps(Uuid id, Uuid router, List<Uuid> networks) {
320         InstanceIdentifier<VpnMap> vpnMapIdentifier = InstanceIdentifier.builder(VpnMaps.class)
321                 .child(VpnMap.class, new VpnMapKey(id)).build();
322         Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
323                 vpnMapIdentifier);
324         if (optionalVpnMap.isPresent()) {
325             VpnMap vpnMap = optionalVpnMap.get();
326             VpnMapBuilder vpnMapBuilder = new VpnMapBuilder(vpnMap);
327             if (router != null) {
328                 if (vpnMap.getNetworkIds() == null && router.equals(vpnMap.getVpnId())) {
329                     // remove entire node in case of internal VPN
330                     logger.debug("removing vpnMaps node: {} ", id);
331                     MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier);
332                     return;
333                 }
334                 vpnMapBuilder.setRouterId(null);
335             }
336             if (networks != null) {
337                 List<Uuid> vpnNw = vpnMap.getNetworkIds();
338                 for (Uuid nw : networks) {
339                     vpnNw.remove(nw);
340                 }
341                 if (vpnNw.isEmpty()) {
342                     logger.debug("setting networks null in vpnMaps node: {} ", id.getValue());
343                     vpnMapBuilder.setNetworkIds(null);
344                 } else {
345                     vpnMapBuilder.setNetworkIds(vpnNw);
346                 }
347             }
348
349             logger.debug("clearing from vpnMaps node: {} ", id.getValue());
350             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnMapIdentifier, vpnMapBuilder.build());
351         } else {
352             logger.error("VPN : {} not found", id.getValue());
353         }
354         logger.debug("VPNMaps DS clear success for VPN {} ", id.getValue());
355     }
356
357     private void deleteVpnInstance(Uuid vpnId) {
358
359         InstanceIdentifier<VpnInstance> vpnIdentifier = InstanceIdentifier.builder(VpnInstances.class).
360                 child(VpnInstance.class, new VpnInstanceKey(vpnId.getValue())).build();
361         logger.debug("removing vpn Instance {}", vpnId.getValue());
362         MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnIdentifier);
363     }
364
365
366     protected void createVpnInterface(Uuid vpnId, Port port) {
367
368         if (vpnId == null || port == null) {
369             return;
370         }
371         String portname = NeutronvpnUtils.uuidToTapPortName(port.getUuid());
372         String name = new StringBuilder(portname).append(":0").toString();
373         List<Adjacency> adjList = new ArrayList<Adjacency>();
374         InstanceIdentifier<VpnInterface> vpnIfIdentifier = InstanceIdentifier.builder(VpnInterfaces.class).
375                 child(VpnInterface.class, new VpnInterfaceKey(name)).build();
376         // find router associated to vpn
377         Uuid routerId = NeutronvpnUtils.getRouterforVpn(broker, vpnId);
378         Router rtr = null;
379         if (routerId != null) {
380             rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
381         }
382         // find all subnets to which this port is associated
383         List<FixedIps> ips = port.getFixedIps();
384         // create adjacency list
385         for (FixedIps ip : ips) {
386             // create vm adjacency
387             StringBuilder IpPrefixBuild = new StringBuilder(ip.getIpAddress().getIpv4Address().getValue());
388             String IpPrefix = IpPrefixBuild.append("/32").toString();
389             Adjacency vmAdj = new AdjacencyBuilder().setKey(new AdjacencyKey(IpPrefix)).setIpAddress(IpPrefix)
390                     .setMacAddress(port.getMacAddress()).build();
391             adjList.add(vmAdj);
392             // create extra route adjacency
393             if (rtr != null && rtr.getRoutes() != null) {
394                 List<String> routeList = rtr.getRoutes();
395                 List<Adjacency> erAdjList = addAdjacencyforExtraRoute(routeList, false, name);
396                 if (erAdjList != null) {
397                     adjList.addAll(erAdjList);
398                 }
399             }
400         }
401         // create vpn-interface on this neutron port
402         Adjacencies adjs = new AdjacenciesBuilder().setAdjacency(adjList).build();
403         VpnInterfaceBuilder vpnb = new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(name)).
404                 setName(name).setVpnInstanceName(vpnId.getValue()).addAugmentation(Adjacencies.class, adjs);
405         VpnInterface vpnIf = vpnb.build();
406
407         NeutronvpnUtils.lockVpnInterface(lockManager, name);
408         try {
409             logger.debug("Creating vpn interface {}", vpnIf);
410             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier, vpnIf);
411         } catch (Exception ex) {
412             logger.error("Creation of vpninterface {} failed due to {}", name, ex);
413         } finally {
414             NeutronvpnUtils.unlockVpnInterface(lockManager, name);
415         }
416     }
417
418     protected void deleteVpnInterface(Port port) {
419
420         if (port != null) {
421             String pname = NeutronvpnUtils.uuidToTapPortName(port.getUuid());
422             String name = new StringBuilder(pname).append(":0").toString();
423             InstanceIdentifier<VpnInterface> vpnIfIdentifier = InstanceIdentifier.builder(VpnInterfaces.class).
424                     child(VpnInterface.class, new VpnInterfaceKey(name)).build();
425
426             NeutronvpnUtils.lockVpnInterface(lockManager, name);
427             try {
428                 logger.debug("Deleting vpn interface {}", name);
429                 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier);
430             } catch (Exception ex) {
431                 logger.error("Deletion of vpninterface {} failed due to {}", name, ex);
432             } finally {
433                 NeutronvpnUtils.unlockVpnInterface(lockManager, name);
434             }
435         }
436     }
437
438     public void createL3Vpn(Uuid vpn, String name, Uuid tenant, List<String> rd, List<String> irt, List<String> ert,
439                             Uuid router, List<Uuid> networks) {
440
441         // Update VPN Instance node
442         updateVpnInstanceNode(vpn.getValue(), rd, irt, ert);
443
444         // Update local vpn-subnet DS
445         updateVpnMaps(vpn, name, router, tenant, networks);
446
447         if (router != null) {
448             associateRouterToVpn(vpn, router);
449         }
450         if (networks != null) {
451             associateNetworksToVpn(vpn, networks);
452         }
453     }
454
455     @Override
456     public Future<RpcResult<CreateL3VPNOutput>> createL3VPN(CreateL3VPNInput input) {
457
458         CreateL3VPNOutputBuilder opBuilder = new CreateL3VPNOutputBuilder();
459         SettableFuture<RpcResult<CreateL3VPNOutput>> result = SettableFuture.create();
460         List<RpcError> errorList = new ArrayList<RpcError>();
461         int failurecount = 0;
462         int warningcount = 0;
463
464         List<L3vpn> vpns = input.getL3vpn();
465         for (L3vpn vpn : vpns) {
466             RpcError error;
467             String msg;
468             if (vpn.getRouteDistinguisher() == null || vpn.getImportRT() == null || vpn.getExportRT() == null) {
469                 msg = String.format("Creation of L3VPN failed for VPN %s due to absence of RD/iRT/eRT input",
470                         vpn.getId().getValue());
471                 logger.warn(msg);
472                 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
473                 errorList.add(error);
474                 warningcount++;
475                 continue;
476             }
477             if (vpn.getRouteDistinguisher().size() > 1) {
478                 msg = String.format("Creation of L3VPN failed for VPN %s due to multiple RD input %s",
479                         vpn.getId().getValue(), vpn.getRouteDistinguisher());
480                 logger.warn(msg);
481                 error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-input", msg);
482                 errorList.add(error);
483                 warningcount++;
484                 continue;
485             }
486             try {
487                 createL3Vpn(vpn.getId(), vpn.getName(), vpn.getTenantId(), vpn.getRouteDistinguisher(),
488                         vpn.getImportRT(), vpn.getExportRT(), vpn.getRouterId(), vpn.getNetworkIds());
489             } catch (Exception ex) {
490                 msg = String.format("Creation of L3VPN failed for VPN %s", vpn.getId().getValue());
491                 logger.error(msg, ex.getMessage());
492                 error = RpcResultBuilder.newError(ErrorType.APPLICATION, msg, ex.getMessage());
493                 errorList.add(error);
494                 failurecount++;
495             }
496         }
497         // if at least one succeeds; result is success
498         // if none succeeds; result is failure
499         if (failurecount + warningcount == vpns.size()) {
500             result.set(RpcResultBuilder.<CreateL3VPNOutput>failed().withRpcErrors(errorList).build());
501         } else {
502             List<String> errorResponseList = new ArrayList<>();
503             if (!errorList.isEmpty()) {
504                 for (RpcError rpcError : errorList) {
505                     String errorResponse = String.format("ErrorType: " + rpcError.getErrorType() + ", " + "ErrorTag: " +
506                             rpcError.getTag() + ", " + "ErrorMessage: " + rpcError.getMessage());
507                     errorResponseList.add(errorResponse);
508                 }
509             } else {
510                 errorResponseList.add("Operation successful with no errors");
511             }
512             opBuilder.setResponse(errorResponseList);
513             result.set(RpcResultBuilder.<CreateL3VPNOutput>success().withResult(opBuilder.build()).build());
514         }
515         return result;
516     }
517
518     @Override
519     public Future<RpcResult<GetL3VPNOutput>> getL3VPN(GetL3VPNInput input) {
520
521         GetL3VPNOutputBuilder opBuilder = new GetL3VPNOutputBuilder();
522         SettableFuture<RpcResult<GetL3VPNOutput>> result = SettableFuture.create();
523         Uuid inputVpnId = input.getId();
524         List<VpnInstance> vpns = new ArrayList<VpnInstance>();
525
526         try {
527             if (inputVpnId == null) {
528                 // get all vpns
529                 InstanceIdentifier<VpnInstances> vpnsIdentifier =
530                         InstanceIdentifier.builder(VpnInstances.class).build();
531                 Optional<VpnInstances> optionalVpns = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
532                         vpnsIdentifier);
533                 if (optionalVpns.isPresent()) {
534                     for (VpnInstance vpn : optionalVpns.get().getVpnInstance()) {
535                         vpns.add(vpn);
536                     }
537                 } else {
538                     // No VPN present
539                     result.set(RpcResultBuilder.<GetL3VPNOutput>failed()
540                             .withWarning(ErrorType.PROTOCOL, "", "No VPN is present").build());
541                     return result;
542                 }
543             } else {
544                 String name = inputVpnId.getValue();
545                 InstanceIdentifier<VpnInstance> vpnIdentifier =
546                         InstanceIdentifier.builder(VpnInstances.class)
547                                 .child(VpnInstance.class, new VpnInstanceKey(name)).build();
548                 // read VpnInstance Info
549                 Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
550                         vpnIdentifier);
551                 if (optionalVpn.isPresent()) {
552                     vpns.add(optionalVpn.get());
553                 } else {
554                     String message = String.format("GetL3VPN failed because VPN %s is not present", name);
555                     logger.error(message);
556                     result.set(RpcResultBuilder.<GetL3VPNOutput>failed()
557                             .withWarning(ErrorType.PROTOCOL, "invalid-value", message).build());
558                 }
559             }
560             List<L3vpnInstances> l3vpnList = new ArrayList<L3vpnInstances>();
561             for (VpnInstance vpnInstance : vpns) {
562                 Uuid vpnId = new Uuid(vpnInstance.getVpnInstanceName());
563                 // create VpnMaps id
564                 InstanceIdentifier<VpnMap> vpnMapIdentifier =
565                         InstanceIdentifier.builder(VpnMaps.class)
566                                 .child(VpnMap.class, new VpnMapKey(vpnId)).build();
567                 L3vpnInstancesBuilder l3vpn = new L3vpnInstancesBuilder();
568
569                 List<String> rd = Arrays.asList(vpnInstance.getIpv4Family().getRouteDistinguisher().split(","));
570                 List<VpnTarget> vpnTargetList = vpnInstance.getIpv4Family().getVpnTargets().getVpnTarget();
571
572                 List<String> ertList = new ArrayList<String>();
573                 List<String> irtList = new ArrayList<String>();
574
575                 for (VpnTarget vpnTarget : vpnTargetList) {
576                     if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.ExportExtcommunity) {
577                         ertList.add(vpnTarget.getVrfRTValue());
578                     }
579                     if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.ImportExtcommunity) {
580                         irtList.add(vpnTarget.getVrfRTValue());
581                     }
582                     if (vpnTarget.getVrfRTType() == VpnTarget.VrfRTType.Both) {
583                         ertList.add(vpnTarget.getVrfRTValue());
584                         irtList.add(vpnTarget.getVrfRTValue());
585                     }
586                 }
587
588                 l3vpn.setId(vpnId).setRouteDistinguisher(rd).setImportRT(irtList).setExportRT(ertList);
589                 Optional<VpnMap> optionalVpnMap = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
590                         vpnMapIdentifier);
591                 if (optionalVpnMap.isPresent()) {
592                     VpnMap vpnMap = optionalVpnMap.get();
593                     l3vpn.setRouterId(vpnMap.getRouterId()).setNetworkIds(vpnMap.getNetworkIds())
594                             .setTenantId(vpnMap.getTenantId()).setName(vpnMap.getName());
595                 }
596                 l3vpnList.add(l3vpn.build());
597             }
598
599             opBuilder.setL3vpnInstances(l3vpnList);
600             result.set(RpcResultBuilder.<GetL3VPNOutput>success().withResult(opBuilder.build()).build());
601
602         } catch (Exception ex) {
603             String message = String.format("GetL3VPN failed due to %s", ex.getMessage());
604             logger.error(message);
605             result.set(RpcResultBuilder.<GetL3VPNOutput>failed().withError(ErrorType.APPLICATION, message).build());
606         }
607
608         return result;
609     }
610
611     @Override
612     public Future<RpcResult<DeleteL3VPNOutput>> deleteL3VPN(DeleteL3VPNInput input) {
613
614         DeleteL3VPNOutputBuilder opBuilder = new DeleteL3VPNOutputBuilder();
615         SettableFuture<RpcResult<DeleteL3VPNOutput>> result = SettableFuture.create();
616         List<RpcError> errorList = new ArrayList<RpcError>();
617
618         int failurecount = 0;
619         int warningcount = 0;
620         List<Uuid> vpns = input.getId();
621         for (Uuid vpn : vpns) {
622             RpcError error;
623             String msg;
624             try {
625                 InstanceIdentifier<VpnInstance> vpnIdentifier =
626                         InstanceIdentifier.builder(VpnInstances.class)
627                                 .child(VpnInstance.class, new VpnInstanceKey(vpn.getValue())).build();
628                 Optional<VpnInstance> optionalVpn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
629                         vpnIdentifier);
630                 if (optionalVpn.isPresent()) {
631                     removeL3Vpn(vpn);
632                 } else {
633                     msg = String.format("VPN with vpnid: %s does not exist", vpn.getValue());
634                     logger.warn(msg);
635                     error = RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "invalid-value", msg);
636                     errorList.add(error);
637                     warningcount++;
638                 }
639             } catch (Exception ex) {
640                 msg = String.format("Deletion of L3VPN failed when deleting for uuid %s", vpn.getValue());
641                 logger.error(msg, ex.getMessage());
642                 error = RpcResultBuilder.newError(ErrorType.APPLICATION, msg, ex.getMessage());
643                 errorList.add(error);
644                 failurecount++;
645             }
646         }
647         // if at least one succeeds; result is success
648         // if none succeeds; result is failure
649         if (failurecount + warningcount == vpns.size()) {
650             result.set(RpcResultBuilder.<DeleteL3VPNOutput>failed().withRpcErrors(errorList).build());
651         } else {
652             List<String> errorResponseList = new ArrayList<>();
653             if (!errorList.isEmpty()) {
654                 for (RpcError rpcError : errorList) {
655                     String errorResponse = String.format("ErrorType: " + rpcError.getErrorType() + ", " + "ErrorTag: " +
656                             rpcError.getTag() + ", " + "ErrorMessage: " + rpcError.getMessage());
657                     errorResponseList.add(errorResponse);
658                 }
659             } else {
660                 errorResponseList.add("Operation successful with no errors");
661             }
662             opBuilder.setResponse(errorResponseList);
663             result.set(RpcResultBuilder.<DeleteL3VPNOutput>success().withResult(opBuilder.build()).build());
664         }
665         return result;
666     }
667
668     protected void addSubnetToVpn(Uuid vpnId, Uuid subnet) {
669         logger.debug("Adding subnet {} to vpn {}", subnet.getValue(), vpnId.getValue());
670         Subnetmap sn = updateSubnetNode(subnet, null, null, null, vpnId, null);
671         // Check if there are ports on this subnet and add corresponding vpn-interfaces
672         List<Uuid> portList = sn.getPortList();
673         if (portList != null) {
674             for (Uuid port : sn.getPortList()) {
675                 logger.debug("adding vpn-interface for port {}", port.getValue());
676                 createVpnInterface(vpnId, getNeutronPort(port));
677             }
678         }
679     }
680
681     protected List<Adjacency> addAdjacencyforExtraRoute(List<String> routeList, boolean rtrUp, String vpnifname) {
682         try {
683             List<Adjacency> adjList = new ArrayList<Adjacency>();
684             for (String route : routeList) {
685                 // assuming extra route is strictly in the format "nexthop destination" > "10.1.1.10 40.0.1.0/24"
686                 String[] parts = route.split(" ");
687                 if (parts.length == 2) {
688                     String nextHop = parts[0];
689                     String destination = parts[1];
690
691                     String tapPortName = NeutronvpnUtils.getNeutronPortNamefromPortFixedIp(broker, nextHop);
692                     String ifname = new StringBuilder(tapPortName).append(":0").toString();
693                     logger.trace("Adding extra route with nexthop {}, destination {}, ifName {}", nextHop,
694                             destination, ifname);
695                     Adjacency erAdj = new AdjacencyBuilder().setIpAddress(destination).setNextHopIp(nextHop).setKey
696                             (new AdjacencyKey(destination)).build();
697                     if (rtrUp == false) {
698                         if (ifname.equals(vpnifname)) {
699                             adjList.add(erAdj);
700                         }
701                         continue;
702                     }
703                     InstanceIdentifier<VpnInterface> vpnIfIdentifier = InstanceIdentifier.builder(VpnInterfaces.class).
704                             child(VpnInterface.class, new VpnInterfaceKey(ifname)).build();
705                     Optional<VpnInterface> optionalVpnInterface = NeutronvpnUtils.read(broker, LogicalDatastoreType
706                             .CONFIGURATION, vpnIfIdentifier);
707                     if (optionalVpnInterface.isPresent()) {
708                         Adjacencies erAdjs = new AdjacenciesBuilder().setAdjacency(Arrays.asList(erAdj)).build();
709                         VpnInterface vpnIf = new VpnInterfaceBuilder().setKey(new VpnInterfaceKey(ifname))
710                                 .addAugmentation(Adjacencies.class, erAdjs).build();
711                         MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION, vpnIfIdentifier, vpnIf);
712                         logger.trace("extra route {} added successfully", route);
713                     } else {
714                         logger.error("VM adjacency for interface {} not present ; cannot add extra route adjacency",
715                                 ifname);
716                     }
717                 } else {
718                     logger.error("Incorrect input received for extra route. {}", parts);
719                 }
720             }
721             return adjList;
722         } catch (Exception e) {
723             logger.error("exception in adding extra route: {}" + e);
724         }
725         return null;
726     }
727
728     protected void removeAdjacencyforExtraRoute(List<String> routeList) {
729         try {
730             for (String route : routeList) {
731                 // assuming extra route is strictly in the format "nexthop destination" > "10.1.1.10 40.0.1.0/24"
732                 String[] parts = route.split(" ");
733                 if (parts.length == 2) {
734                     String nextHop = parts[0];
735                     String destination = parts[1];
736
737                     String tapPortName = NeutronvpnUtils.getNeutronPortNamefromPortFixedIp(broker, nextHop);
738                     String ifname = new StringBuilder(tapPortName).append(":0").toString();
739                     logger.trace("Removing extra route with nexthop {}, destination {}, ifName {}", nextHop,
740                             destination, ifname);
741                     InstanceIdentifier<Adjacency> adjacencyIdentifier = InstanceIdentifier.builder(VpnInterfaces.class).
742                             child(VpnInterface.class, new VpnInterfaceKey(ifname)).augmentation(Adjacencies.class)
743                             .child(Adjacency.class, new AdjacencyKey(destination)).build();
744                     MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, adjacencyIdentifier);
745                     logger.trace("extra route {} deleted successfully", route);
746                 } else {
747                     logger.error("Incorrect input received for extra route. {}", parts);
748                 }
749             }
750         } catch (Exception e) {
751             logger.error("exception in deleting extra route: {}" + e);
752         }
753     }
754
755     protected void addPortToVpn(Uuid vpnId, Uuid port) {
756         logger.debug("Adding Port to vpn node...");
757         createVpnInterface(vpnId, getNeutronPort(port));
758     }
759
760     protected void removeL3Vpn(Uuid id) {
761         // read VPN networks
762         VpnMap vpnMap = NeutronvpnUtils.getVpnMap(broker, id);
763         Uuid router = vpnMap.getRouterId();
764         // dissociate router
765         if (router != null) {
766             dissociateRouterFromVpn(id, router);
767         }
768         // dissociate networks
769         if (!id.equals(router)) {
770             dissociateNetworksFromVpn(id, vpnMap.getNetworkIds());
771         }
772         // remove entire vpnMaps node
773         deleteVpnMapsNode(id);
774
775         // remove vpn-instance
776         deleteVpnInstance(id);
777     }
778
779     protected void removePortFromVpn(Uuid vpnId, Uuid port) {
780         logger.debug("Removing Port from vpn node...");
781         deleteVpnInterface(getNeutronPort(port));
782     }
783
784     protected void removeSubnetFromVpn(Uuid vpnId, Uuid subnet) {
785         logger.debug("Removing subnet {} from vpn {}", subnet.getValue(), vpnId.getValue());
786         Subnetmap sn = NeutronvpnUtils.getSubnetmap(broker, subnet);
787         if (sn != null) {
788             // Check if there are ports on this subnet; remove corresponding vpn-interfaces
789             List<Uuid> portList = sn.getPortList();
790             if (portList != null) {
791                 for (Uuid port : sn.getPortList()) {
792                     logger.debug("removing vpn-interface for port {}", port.getValue());
793                     deleteVpnInterface(getNeutronPort(port));
794                 }
795             }
796             // update subnet-vpn association
797             removeFromSubnetNode(subnet, null, null, vpnId, null);
798         } else {
799             logger.warn("Subnetmap for subnet {} not found", subnet.getValue());
800         }
801     }
802
803     protected void associateRouterToVpn(Uuid vpn, Uuid router) {
804
805         // remove existing Router-VPN
806         if (!vpn.equals(router)) {
807             removeL3Vpn(router);
808         }
809         updateVpnMaps(vpn, null, router, null, null);
810
811         List<Uuid> routerSubnets = NeutronvpnUtils.getNeutronRouterSubnetIds(broker, router);
812         logger.debug("Adding subnets...");
813         for (Uuid subnet : routerSubnets) {
814             addSubnetToVpn(vpn, subnet);
815         }
816     }
817
818     protected void dissociateRouterFromVpn(Uuid vpn, Uuid router) {
819         clearFromVpnMaps(vpn, router, null);
820
821         // fetching sn from SubnetmapDS for internal VPN because sn already deleted from RouterIf DS on router deletion
822         List<Uuid> routerSubnets = (vpn.equals(router)) ? getSubnetsforVpn(vpn) :
823                 NeutronvpnUtils.getNeutronRouterSubnetIds(broker, router);
824
825         logger.debug("dissociateRouter vpn {} router {} Removing subnets...", vpn.getValue(), router.getValue());
826         if (routerSubnets != null) {
827             for (Uuid subnet : routerSubnets) {
828                 removeSubnetFromVpn(vpn, subnet);
829             }
830         }
831         // create Router-VPN for this router
832         if (!vpn.equals(router)) {
833             logger.debug("Re-creating vpn-router...");
834             createL3Vpn(router, null, null, null, null, null, router, null);
835         }
836     }
837
838     protected List<String> associateNetworksToVpn(Uuid vpn, List<Uuid> networks) {
839         List<String> failed = new ArrayList<String>();
840         if (!networks.isEmpty()) {
841             // store in Data Base
842             updateVpnMaps(vpn, null, null, null, networks);
843             // process corresponding subnets for VPN
844             for (Uuid nw : networks) {
845                 if (NeutronvpnUtils.getNeutronNetwork(broker, nw) == null) {
846                     failed.add(nw.getValue());
847                 } else {
848                     List<Uuid> networkSubnets = NeutronvpnUtils.getSubnetIdsFromNetworkId(broker, nw);
849                     logger.debug("Adding network subnets...");
850                     if (networkSubnets != null) {
851                         for (Uuid subnet : networkSubnets) {
852                             addSubnetToVpn(vpn, subnet);
853                         }
854                     }
855                 }
856             }
857         }
858         return failed;
859     }
860
861     protected List<String> dissociateNetworksFromVpn(Uuid vpn, List<Uuid> networks) {
862         List<String> failed = new ArrayList<String>();
863         if (networks != null && !networks.isEmpty()) {
864             // store in Data Base
865             clearFromVpnMaps(vpn, null, networks);
866             // process corresponding subnets for VPN
867             for (Uuid nw : networks) {
868                 if (NeutronvpnUtils.getNeutronNetwork(broker, nw) == null) {
869                     failed.add(nw.getValue());
870                 } else {
871                     List<Uuid> networkSubnets = NeutronvpnUtils.getSubnetIdsFromNetworkId(broker, nw);
872                     logger.debug("Removing network subnets...");
873                     if (networkSubnets != null) {
874                         for (Uuid subnet : networkSubnets) {
875                             removeSubnetFromVpn(vpn, subnet);
876                         }
877                     }
878                 }
879             }
880         }
881         return failed;
882     }
883
884     @Override
885     public Future<RpcResult<AssociateNetworksOutput>> associateNetworks(AssociateNetworksInput input) {
886
887         AssociateNetworksOutputBuilder opBuilder = new AssociateNetworksOutputBuilder();
888         SettableFuture<RpcResult<AssociateNetworksOutput>> result = SettableFuture.create();
889         logger.debug("associateNetworks {}", input);
890         StringBuilder returnMsg = new StringBuilder();
891         Uuid vpnId = input.getVpnId();
892
893         try {
894             if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
895                 List<Uuid> netIds = input.getNetworkId();
896                 if (netIds != null && !netIds.isEmpty()) {
897                     List<String> failed = associateNetworksToVpn(vpnId, netIds);
898                     if (!failed.isEmpty()) {
899                         returnMsg.append("network(s) not found : ").append(failed);
900                     }
901                 }
902             } else {
903                 returnMsg.append("VPN not found : ").append(vpnId.getValue());
904             }
905             if (returnMsg.length() != 0) {
906                 String message = String.format("associate Networks to vpn %s failed due to %s", vpnId.getValue(),
907                         returnMsg);
908                 logger.error(message);
909                 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
910                         message);
911                 opBuilder.setResponse(errorResponse);
912                 result.set(RpcResultBuilder.<AssociateNetworksOutput>success().withResult(opBuilder.build()).build());
913             } else {
914                 result.set(RpcResultBuilder.<AssociateNetworksOutput>success().build());
915             }
916         } catch (Exception ex) {
917             String message = String.format("associate Networks to vpn %s failed due to %s", input.getVpnId().getValue(),
918                     ex.getMessage());
919             logger.error(message);
920             result.set(RpcResultBuilder.<AssociateNetworksOutput>failed().withError(ErrorType.APPLICATION, message)
921                     .build());
922         }
923         logger.debug("associateNetworks returns..");
924         return result;
925     }
926
927     @Override
928     public Future<RpcResult<Void>> associateRouter(AssociateRouterInput input) {
929
930         SettableFuture<RpcResult<Void>> result = SettableFuture.create();
931         logger.debug("associateRouter {}", input);
932         StringBuilder returnMsg = new StringBuilder();
933         Uuid vpnId = input.getVpnId();
934         Uuid routerId = input.getRouterId();
935         try {
936             if (routerId != null && vpnId != null) {
937                 Router rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
938                 VpnMap vpnMap = NeutronvpnUtils.getVpnMap(broker, vpnId);
939                 if (rtr != null && vpnMap != null) {
940                     if (vpnMap.getRouterId() != null) {
941                         returnMsg.append("vpn ").append(vpnId.getValue()).append(" already associated to router ")
942                                 .append(vpnMap.getRouterId().getValue());
943                     } else {
944                         associateRouterToVpn(vpnId, routerId);
945                     }
946                 } else {
947                     returnMsg.append("router not found : ").append(routerId.getValue());
948                 }
949             } else {
950                 returnMsg.append("VPN not found : ").append(vpnId.getValue());
951             }
952             if (returnMsg.length() != 0) {
953                 String message = String.format("associate router to vpn %s failed due to %s", routerId.getValue(),
954                         returnMsg);
955                 logger.error(message);
956                 result.set(RpcResultBuilder.<Void>failed().withWarning(ErrorType.PROTOCOL, "invalid-value", message)
957                         .build());
958             } else {
959                 result.set(RpcResultBuilder.<Void>success().build());
960             }
961         } catch (Exception ex) {
962             String message = String.format("associate router %s to vpn %s failed due to %s", routerId.getValue(),
963                     vpnId.getValue(), ex.getMessage());
964             logger.error(message);
965             result.set(RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, message).build());
966         }
967         logger.debug("associateRouter returns..");
968         return result;
969     }
970
971     @Override
972     public Future<RpcResult<DissociateNetworksOutput>> dissociateNetworks(DissociateNetworksInput input) {
973
974         DissociateNetworksOutputBuilder opBuilder = new DissociateNetworksOutputBuilder();
975         SettableFuture<RpcResult<DissociateNetworksOutput>> result = SettableFuture.create();
976
977         logger.debug("dissociateNetworks {}", input);
978         StringBuilder returnMsg = new StringBuilder();
979         Uuid vpnId = input.getVpnId();
980
981         try {
982             if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
983                 List<Uuid> netIds = input.getNetworkId();
984                 if (netIds != null && !netIds.isEmpty()) {
985                     List<String> failed = dissociateNetworksFromVpn(vpnId, netIds);
986                     if (!failed.isEmpty()) {
987                         returnMsg.append("netowrk(s) not found : ").append(failed);
988                     }
989                 }
990             } else {
991                 returnMsg.append("VPN not found : ").append(vpnId.getValue());
992             }
993             if (returnMsg.length() != 0) {
994                 String message = String.format("disssociate Networks to vpn %s failed due to %s", vpnId.getValue(),
995                         returnMsg);
996                 logger.error(message);
997                 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
998                         message);
999                 opBuilder.setResponse(errorResponse);
1000                 result.set(RpcResultBuilder.<DissociateNetworksOutput>success().withResult(opBuilder.build()).build());
1001             } else {
1002                 result.set(RpcResultBuilder.<DissociateNetworksOutput>success().build());
1003             }
1004         } catch (Exception ex) {
1005             String message = String.format("dissociate Networks to vpn %s failed due to %s", input.getVpnId().
1006                     getValue(), ex.getMessage());
1007             logger.error(message);
1008             result.set(RpcResultBuilder.<DissociateNetworksOutput>failed().withError(ErrorType.APPLICATION, message)
1009                     .build());
1010         }
1011         logger.debug("dissociateNetworks returns..");
1012         return result;
1013     }
1014
1015     @Override
1016     public Future<RpcResult<Void>> dissociateRouter(DissociateRouterInput input) {
1017
1018         SettableFuture<RpcResult<Void>> result = SettableFuture.create();
1019
1020         logger.debug("dissociateRouter {}", input);
1021         StringBuilder returnMsg = new StringBuilder();
1022         Uuid vpnId = input.getVpnId();
1023         Uuid routerId = input.getRouterId();
1024         try {
1025             if (NeutronvpnUtils.getVpnMap(broker, vpnId) != null) {
1026                 if (routerId != null) {
1027                     Router rtr = NeutronvpnUtils.getNeutronRouter(broker, routerId);
1028                     if (rtr != null) {
1029                         dissociateRouterFromVpn(vpnId, routerId);
1030                     } else {
1031                         returnMsg.append("router not found : ").append(routerId.getValue());
1032                     }
1033                 }
1034             } else {
1035                 returnMsg.append("VPN not found : ").append(vpnId.getValue());
1036             }
1037             if (returnMsg.length() != 0) {
1038                 String message = String.format("disssociate router %s to vpn %s failed due to %s", routerId.getValue(),
1039                         vpnId.getValue(), returnMsg);
1040                 logger.error(message);
1041                 String errorResponse = String.format("ErrorType: PROTOCOL, ErrorTag: invalid-value, ErrorMessage: " +
1042                         message);
1043                 result.set(RpcResultBuilder.<Void>failed().withWarning(ErrorType.PROTOCOL, "invalid-value", message)
1044                         .build());
1045             } else {
1046                 result.set(RpcResultBuilder.<Void>success().build());
1047             }
1048         } catch (Exception ex) {
1049             String message = String.format("disssociate router %s to vpn %s failed due to %s", routerId.getValue(),
1050                     vpnId.getValue(), ex.getMessage());
1051             logger.error(message);
1052             result.set(RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION, message).build());
1053         }
1054         logger.debug("dissociateRouter returns..");
1055
1056         return result;
1057     }
1058
1059     protected Subnet getNeutronSubnet(Uuid subnetId) {
1060         InstanceIdentifier<Subnet> inst = InstanceIdentifier.create(Neutron.class).
1061                 child(Subnets.class).child(Subnet.class, new SubnetKey(subnetId));
1062         Optional<Subnet> sn = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, inst);
1063
1064         if (sn.isPresent()) {
1065             return sn.get();
1066         }
1067         return null;
1068     }
1069
1070     protected IpAddress getNeutronSubnetGateway(Uuid subnetId) {
1071         Subnet sn = getNeutronSubnet(subnetId);
1072         if (null != sn) {
1073             return sn.getGatewayIp();
1074         }
1075         return null;
1076     }
1077
1078     protected Port getNeutronPort(String name) {
1079         Uuid portId = NeutronvpnUtils.getNeutronPortIdfromPortName(broker, name);
1080         if (portId != null) {
1081             InstanceIdentifier<Port> pid = InstanceIdentifier.create(Neutron.class).
1082                     child(Ports.class).child(Port.class, new PortKey(portId));
1083             Optional<Port> optPort = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, pid);
1084             if (optPort.isPresent()) {
1085                 return optPort.get();
1086             }
1087         } else {
1088             logger.error("Port {} not Found!!", name);
1089         }
1090         return null;
1091     }
1092
1093     protected Port getNeutronPort(Uuid portId) {
1094         InstanceIdentifier<Port> pid = InstanceIdentifier.create(Neutron.class).
1095                 child(Ports.class).child(Port.class, new PortKey(portId));
1096         Optional<Port> optPort = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, pid);
1097         if (optPort.isPresent()) {
1098             return optPort.get();
1099         }
1100         return null;
1101     }
1102
1103     protected List<Uuid> getSubnetsforVpn(Uuid vpnid) {
1104         List<Uuid> subnets = new ArrayList<Uuid>();
1105         //read subnetmaps
1106         InstanceIdentifier<Subnetmaps> subnetmapsid = InstanceIdentifier.builder(Subnetmaps.class).build();
1107         Optional<Subnetmaps> subnetmaps = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
1108                 subnetmapsid);
1109         if (subnetmaps.isPresent()) {
1110             Subnetmaps smaps = subnetmaps.get();
1111             List<Subnetmap> subnetMapList = smaps.getSubnetmap();
1112             for (Subnetmap subnetMap : subnetMapList) {
1113                 if (subnetMap.getVpnId() != null && subnetMap.getVpnId().equals(vpnid)) {
1114                     subnets.add(subnetMap.getId());
1115                 }
1116             }
1117         }
1118         return subnets;
1119     }
1120
1121     public List<String> showNeutronPortsCLI() {
1122         List<String> result = new ArrayList<String>();
1123         result.add(String.format(" %-22s  %-22s  %-22s  %-6s ", "PortName", "Mac Address", "IP Address",
1124                 "Prefix Length"));
1125         result.add("---------------------------------------------------------------------------------------");
1126         InstanceIdentifier<Ports> portidentifier = InstanceIdentifier.create(Neutron.class).child(Ports.class);
1127         try {
1128             Optional<Ports> ports = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION, portidentifier);
1129             if (ports.isPresent()) {
1130                 List<Port> portList = ports.get().getPort();
1131                 for (Port port : portList) {
1132                     result.add(String.format(" %-22s  %-22s  %-22s  %-6s ", NeutronvpnUtils.uuidToTapPortName(port
1133                             .getUuid()), port.getMacAddress(), port.getFixedIps().get(0).getIpAddress().getIpv4Address()
1134                             .getValue(), NeutronvpnUtils.getIPPrefixFromPort(broker, port)));
1135                 }
1136             }
1137         } catch (Exception e) {
1138             logger.trace("Failed to retrieve neutronPorts info : ", e);
1139             System.out.println("Failed to retrieve neutronPorts info : " + e.getMessage());
1140         }
1141         return result;
1142     }
1143
1144     public List<String> showVpnConfigCLI(Uuid vpnuuid) {
1145         List<String> result = new ArrayList<String>();
1146         if (vpnuuid == null) {
1147             System.out.println("");
1148             System.out.println("Displaying VPN config for all VPNs");
1149             System.out.println("To display VPN config for a particular VPN, use the following syntax");
1150             System.out.println(getshowVpnConfigCLIHelp());
1151         }
1152         try {
1153             RpcResult<GetL3VPNOutput> rpcResult = getL3VPN(new GetL3VPNInputBuilder().setId(vpnuuid).build()).get();
1154             if (rpcResult.isSuccessful()) {
1155                 result.add("");
1156                 result.add(String.format(" %-37s %-37s %-7s ", "VPN ID", "Tenant ID", "RD"));
1157                 result.add("");
1158                 result.add(String.format(" %-80s ", "Import-RTs"));
1159                 result.add("");
1160                 result.add(String.format(" %-80s ", "Export-RTs"));
1161                 result.add("");
1162                 result.add(String.format(" %-76s ", "Subnet IDs"));
1163                 result.add("");
1164                 result.add("------------------------------------------------------------------------------------");
1165                 result.add("");
1166                 List<L3vpnInstances> VpnList = rpcResult.getResult().getL3vpnInstances();
1167                 for (L3vpnInstance Vpn : VpnList) {
1168                     String tenantId = Vpn.getTenantId() != null ? Vpn.getTenantId().getValue() : "\"                 " +
1169                             "                  \"";
1170                     result.add(String.format(" %-37s %-37s %-7s ", Vpn.getId().getValue(), tenantId, Vpn
1171                             .getRouteDistinguisher()));
1172                     result.add("");
1173                     result.add(String.format(" %-80s ", Vpn.getImportRT()));
1174                     result.add("");
1175                     result.add(String.format(" %-80s ", Vpn.getExportRT()));
1176                     result.add("");
1177
1178                     Uuid vpnid = Vpn.getId();
1179                     List<Uuid> subnetList = getSubnetsforVpn(vpnid);
1180                     if (!subnetList.isEmpty()) {
1181                         for (Uuid subnetuuid : subnetList) {
1182                             result.add(String.format(" %-76s ", subnetuuid.getValue()));
1183                         }
1184                     } else {
1185                         result.add(String.format(" %-76s ", "\"                                    \""));
1186                     }
1187                     result.add("");
1188                     result.add("----------------------------------------");
1189                     result.add("");
1190                 }
1191             } else {
1192                 String errortag = rpcResult.getErrors().iterator().next().getTag();
1193                 if (errortag == "") {
1194                     System.out.println("");
1195                     System.out.println("No VPN has been configured yet");
1196                 } else if (errortag == "invalid-value") {
1197                     System.out.println("");
1198                     System.out.println("VPN " + vpnuuid.getValue() + " is not present");
1199                 } else {
1200                     System.out.println("error getting VPN info : " + rpcResult.getErrors());
1201                     System.out.println(getshowVpnConfigCLIHelp());
1202                 }
1203             }
1204         } catch (InterruptedException | ExecutionException e) {
1205             logger.trace("error getting VPN info : ", e);
1206             System.out.println("error getting VPN info : " + e.getMessage());
1207         }
1208         return result;
1209     }
1210
1211     private String getshowVpnConfigCLIHelp() {
1212         StringBuilder help = new StringBuilder("Usage:");
1213         help.append("display vpn-config [-vid/--vpnid <id>]");
1214         return help.toString();
1215     }
1216
1217 }