Multiple fixes in neutronvpn code
[netvirt.git] / vpnservice / neutronvpn / neutronvpn-impl / src / main / java / org / opendaylight / netvirt / neutronvpn / NeutronPortChangeListener.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
11 import com.google.common.base.Optional;
12 import com.google.common.collect.Lists;
13
14 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
15 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
16 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
17 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
18 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
19 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
20 import org.opendaylight.genius.mdsalutil.AbstractDataChangeListener;
21 import org.opendaylight.genius.mdsalutil.MDSALUtil;
22 import org.opendaylight.netvirt.neutronvpn.api.utils.NeutronUtils;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.L2vlan;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.FloatingIpInfo;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.RouterPorts;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.RouterPortsKey;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.PortsKey;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.api.rev160608.InterfaceAclBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.api.rev160608.InterfaceAcl;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlan;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlanBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefsBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.LockManagerService;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.PortAddedToSubnetBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.PortRemovedFromSubnetBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.neutron.port.data
52         .PortFixedipToPortNameBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
54 import org.opendaylight.yangtools.concepts.ListenerRegistration;
55 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import java.util.ArrayList;
60 import java.util.Iterator;
61 import java.util.List;
62
63
64 public class NeutronPortChangeListener extends AbstractDataChangeListener<Port> implements AutoCloseable {
65     private static final Logger LOG = LoggerFactory.getLogger(NeutronPortChangeListener.class);
66
67     private ListenerRegistration<DataChangeListener> listenerRegistration;
68     private final DataBroker broker;
69     private NeutronvpnManager nvpnManager;
70     private NeutronvpnNatManager nvpnNatManager;
71     private LockManagerService lockManager;
72     private NotificationPublishService notificationPublishService;
73     private NotificationService notificationService;
74     private NeutronFloatingToFixedIpMappingChangeListener floatingIpMapListener;
75
76
77     public NeutronPortChangeListener(final DataBroker db, NeutronvpnManager nVpnMgr,NeutronvpnNatManager nVpnNatMgr,
78                                      NotificationPublishService notiPublishService, NotificationService notiService,
79                                      NeutronFloatingToFixedIpMappingChangeListener neutronFloatingToFixedIpMappingChangeListener) {
80         super(Port.class);
81         broker = db;
82         nvpnManager = nVpnMgr;
83         nvpnNatManager = nVpnNatMgr;
84         notificationPublishService = notiPublishService;
85         notificationService = notiService;
86         floatingIpMapListener = neutronFloatingToFixedIpMappingChangeListener;
87         registerListener(db);
88     }
89
90     public void setLockManager(LockManagerService lockManager) {
91         this.lockManager = lockManager;
92     }
93
94     @Override
95     public void close() throws Exception {
96         if (listenerRegistration != null) {
97             try {
98                 listenerRegistration.close();
99             } catch (final Exception e) {
100                 LOG.error("Error when cleaning up DataChangeListener.", e);
101             }
102             listenerRegistration = null;
103         }
104         LOG.info("N_Port listener Closed");
105     }
106
107
108     private void registerListener(final DataBroker db) {
109         try {
110             listenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION,
111                     InstanceIdentifier.create(Neutron.class).child(Ports.class).child(Port.class),
112                     NeutronPortChangeListener.this, DataChangeScope.SUBTREE);
113         } catch (final Exception e) {
114             LOG.error("Neutron Manager Port DataChange listener registration fail!", e);
115             throw new IllegalStateException("Neutron Manager Port DataChange listener registration failed.", e);
116         }
117     }
118
119     @Override
120     protected void add(InstanceIdentifier<Port> identifier, Port input) {
121         if (LOG.isTraceEnabled()) {
122             LOG.trace("Adding Port : key: " + identifier + ", value=" + input);
123         }
124         Network network = NeutronvpnUtils.getNeutronNetwork(broker, input.getNetworkId());
125         if (network == null || NeutronvpnUtils.isNetworkTypeVlanOrGre(network)) {
126             //FIXME: This should be removed when support for VLAN and GRE network types is added
127             LOG.error("neutron vpn doesn't support vlan/gre network provider type for the port {} which is part of network {}.",
128                     input.getName(), network);
129             return;
130         }
131         /* check if router interface has been created */
132         if ((input.getDeviceOwner() != null) && (input.getDeviceId() != null)) {
133             if (input.getDeviceOwner().equals(NeutronConstants.DEVICE_OWNER_ROUTER_INF)) {
134                 handleRouterInterfaceAdded(input);
135                 /* nothing else to do here */
136                 return;
137             }
138         }
139         handleNeutronPortCreated(input);
140         NeutronvpnUtils.addToPortCache(input);
141
142     }
143
144     @Override
145     protected void remove(InstanceIdentifier<Port> identifier, Port input) {
146         if (LOG.isTraceEnabled()) {
147             LOG.trace("Removing Port : key: " + identifier + ", value=" + input);
148         }
149         Network network = NeutronvpnUtils.getNeutronNetwork(broker, input.getNetworkId());
150         if (network == null || NeutronvpnUtils.isNetworkTypeVlanOrGre(network)) {
151             //FIXME: This should be removed when support for VLAN and GRE network types is added
152             LOG.error("neutron vpn doesn't support vlan/gre network provider type for the port {} which is part of network {}.",
153                     input.getName(), network);
154             return;
155         }
156         if ((input.getDeviceOwner() != null) && (input.getDeviceId() != null)) {
157             if (input.getDeviceOwner().equals(NeutronConstants.DEVICE_OWNER_ROUTER_INF)) {
158                 handleRouterInterfaceRemoved(input);
159                 /* nothing else to do here */
160                 return;
161             }
162         }
163         handleNeutronPortDeleted(input);
164         NeutronvpnUtils.removeFromPortCache(input);
165     }
166
167     @Override
168     protected void update(InstanceIdentifier<Port> identifier, Port original, Port update) {
169         if (LOG.isTraceEnabled()) {
170             LOG.trace("Updating Port : key: " + identifier + ", original value=" + original + ", update value=" +
171                     update);
172         }
173
174         Network network = NeutronvpnUtils.getNeutronNetwork(broker, update.getNetworkId());
175         if (network == null || NeutronvpnUtils.isNetworkTypeVlanOrGre(network)) {
176             LOG.error("neutron vpn doesn't support vlan/gre network provider type for the port {} which is part of network {}."
177                     + " Skipping the processing of Port update DCN", update.getName(), network);
178             return;
179         }
180         List<FixedIps> oldIPs = (original.getFixedIps() != null) ? original.getFixedIps() : new ArrayList<FixedIps>();
181         List<FixedIps> newIPs = (update.getFixedIps() != null) ? update.getFixedIps() : new ArrayList<FixedIps>();
182
183         /* check if VIF type updated as part of port binding */
184         if (NeutronvpnUtils.isPortVifTypeUpdated(original, update)) {
185             updateOfPortInterface(original, update);
186         }
187
188         /* check if router interface has been updated */
189         if ((update.getDeviceOwner() != null) && (update.getDeviceId() != null)) {
190             if (update.getDeviceOwner().equals(NeutronConstants.DEVICE_OWNER_ROUTER_INF)) {
191                 handleRouterInterfaceAdded(update);
192                 /* nothing else to do here */
193                 return;
194             }
195         }
196
197         if (!oldIPs.equals(newIPs)) {
198             Iterator<FixedIps> iterator = newIPs.iterator();
199             while (iterator.hasNext()) {
200                 FixedIps ip = iterator.next();
201                 if (oldIPs.remove(ip)) {
202                     iterator.remove();
203                 }
204             }
205             handleNeutronPortUpdated(original, update);
206             NeutronvpnUtils.addToPortCache(update);
207         }
208
209         handlePortSecurityUpdated(original, update);
210     }
211
212     private void handleRouterInterfaceAdded(Port routerPort) {
213         if (routerPort.getDeviceId() != null) {
214             Uuid routerId = new Uuid(routerPort.getDeviceId());
215             Uuid infNetworkId = routerPort.getNetworkId();
216             Uuid existingVpnId = NeutronvpnUtils.getVpnForNetwork(broker, infNetworkId);
217             if (existingVpnId == null) {
218                 for (FixedIps portIP : routerPort.getFixedIps()) {
219                     if (portIP.getIpAddress().getIpv4Address() != null) {
220                         Uuid vpnId = NeutronvpnUtils.getVpnForRouter(broker, routerId, true);
221                         if (vpnId == null) {
222                             vpnId = routerId;
223                         }
224                         nvpnManager.addSubnetToVpn(vpnId, portIP.getSubnetId());
225                         nvpnNatManager.handleSubnetsForExternalRouter(routerId, broker);
226                     }
227                 }
228             } else {
229                 LOG.warn("Neutron network {} corresponding to router interface port {} for neutron router {} already " +
230                         "associated to VPN {}", infNetworkId.getValue(), routerPort.getUuid().getValue(), routerId
231                         .getValue(), existingVpnId.getValue());
232             }
233         }
234     }
235
236     private void handleRouterInterfaceRemoved(Port routerPort) {
237         if (routerPort.getDeviceId() != null) {
238             Uuid routerId = new Uuid(routerPort.getDeviceId());
239             for (FixedIps portIP : routerPort.getFixedIps()) {
240                 if (portIP.getIpAddress().getIpv4Address() != null) {
241                     Uuid vpnId = NeutronvpnUtils.getVpnForRouter(broker, routerId, true);
242                     if(vpnId == null) {
243                         vpnId = routerId;
244                     }
245                     nvpnManager.removeSubnetFromVpn(vpnId, portIP.getSubnetId());
246                     nvpnNatManager.handleSubnetsForExternalRouter(routerId, broker);
247                 }
248             }
249         }
250     }
251
252     private void handleNeutronPortCreated(Port port) {
253         if (!NeutronUtils.isPortVnicTypeNormal(port)) {
254             LOG.info("Port {} is not a NORMAL VNIC Type port; OF Port interfaces are not created",
255                     port.getUuid().getValue());
256             return;
257         }
258         LOG.info("Of-port-interface creation");
259         // Create of-port interface for this neutron port
260         String portInterfaceName = createOfPortInterface(port);
261         LOG.debug("Creating ELAN Interface");
262         createElanInterface(port, portInterfaceName);
263         LOG.debug("Add port to subnet");
264         // add port to local Subnets DS
265         Uuid vpnId = addPortToSubnets(port);
266
267         if (vpnId != null) {
268             // create vpn-interface on this neutron port
269             LOG.debug("Adding VPN Interface");
270             nvpnManager.createVpnInterface(vpnId, port);
271             Uuid routerId = NeutronvpnUtils.getVpnMap(broker, vpnId).getRouterId();
272             if(routerId != null) {
273                 nvpnManager.addToNeutronRouterInterfacesMap(routerId, port.getUuid().getValue());
274             }
275         }
276     }
277
278     private void handleNeutronPortDeleted(Port port) {
279         //dissociate fixedIP from floatingIP if associated
280         floatingIpMapListener.dissociatefixedIPFromFloatingIP(port.getUuid().getValue());
281         LOG.debug("Remove port from subnet");
282         // remove port from local Subnets DS
283         Uuid vpnId = removePortFromSubnets(port);
284
285         if (vpnId != null) {
286             // remove vpn-interface for this neutron port
287             LOG.debug("removing VPN Interface");
288             nvpnManager.deleteVpnInterface(port);
289         }
290         // Remove of-port interface for this neutron port
291         // ELAN interface is also implicitly deleted as part of this operation
292         LOG.debug("Of-port-interface removal", port);
293         deleteOfPortInterface(port);
294
295         Uuid routerId = NeutronvpnUtils.getVpnMap(broker, vpnId).getRouterId();
296         if(routerId != null) {
297             nvpnManager.removeFromNeutronRouterInterfacesMap(routerId, port.getUuid().getValue());
298         }
299
300     }
301
302     private void handleNeutronPortUpdated(Port portoriginal, Port portupdate) {
303         LOG.debug("Add port to subnet");
304         // add port FixedIP to local Subnets DS
305         Uuid vpnIdup = addPortToSubnets(portupdate);
306
307         if (vpnIdup != null) {
308             nvpnManager.createVpnInterface(vpnIdup, portupdate);
309             Uuid routerId = NeutronvpnUtils.getVpnMap(broker, vpnIdup).getRouterId();
310             if(routerId != null) {
311                 nvpnManager.addToNeutronRouterInterfacesMap(routerId, portupdate.getUuid().getValue());
312             }
313         }
314
315         // remove port FixedIP from local Subnets DS
316         Uuid vpnIdor = removePortFromSubnets(portoriginal);
317
318         if (vpnIdor != null) {
319             nvpnManager.deleteVpnInterface(portoriginal);
320             Uuid routerId = NeutronvpnUtils.getVpnMap(broker, vpnIdor).getRouterId();
321             if(routerId != null) {
322                 nvpnManager.removeFromNeutronRouterInterfacesMap(routerId, portoriginal.getUuid().getValue());
323             }
324         }
325     }
326
327     private void handlePortSecurityUpdated(Port portOriginal, Port portUpdated) {
328         Boolean origSecurityEnabled = NeutronvpnUtils.getPortSecurityEnabled(portOriginal);
329         Boolean updatedSecurityEnabled = NeutronvpnUtils.getPortSecurityEnabled(portUpdated);
330         String interfaceName = portUpdated.getUuid().getValue();
331         Interface portInterface = NeutronvpnUtils.getOfPortInterface(broker, portUpdated);
332         if (portInterface != null) {
333             InterfaceAclBuilder interfaceAclBuilder = null;
334             if (origSecurityEnabled != updatedSecurityEnabled) {
335                 interfaceAclBuilder = new InterfaceAclBuilder();
336                 interfaceAclBuilder.setPortSecurityEnabled(updatedSecurityEnabled);
337                 if (updatedSecurityEnabled) {
338                     // Handle security group enabled
339                     List<Uuid> securityGroups = portUpdated.getSecurityGroups();
340                     if (securityGroups != null) {
341                         interfaceAclBuilder.setSecurityGroups(securityGroups);
342                     }
343                 } else {
344                     // Handle security group disabled
345                     interfaceAclBuilder.setSecurityGroups(Lists.newArrayList());
346                 }
347             } else {
348                 if (updatedSecurityEnabled) {
349                     // handle SG add/delete delta
350                     InterfaceAcl interfaceAcl = portInterface.getAugmentation(InterfaceAcl.class);
351                     interfaceAclBuilder = new InterfaceAclBuilder(interfaceAcl);
352                     List<Uuid> addedGroups = getsecurityGroupChanged(portUpdated.getSecurityGroups(),
353                             portOriginal.getSecurityGroups());
354                     List<Uuid> deletedGroups = getsecurityGroupChanged(portOriginal.getSecurityGroups(),
355                             portUpdated.getSecurityGroups());
356                     List<Uuid> securityGroups = interfaceAcl.getSecurityGroups();
357                     if (addedGroups != null) {
358                         securityGroups.addAll(addedGroups);
359                     }
360                     if (deletedGroups != null) {
361                         securityGroups.removeAll(deletedGroups);
362                     }
363                     interfaceAclBuilder.setSecurityGroups(securityGroups);
364                 }
365             }
366
367             if (interfaceAclBuilder != null) {
368                 InterfaceBuilder builder = new InterfaceBuilder(portInterface)
369                         .addAugmentation(InterfaceAcl.class, interfaceAclBuilder.build());
370                 InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(interfaceName);
371                 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, interfaceIdentifier, builder.build());
372             }
373         } else {
374             LOG.error("Interface {} is not present", interfaceName);
375         }
376     }
377
378     private List<Uuid> getsecurityGroupChanged(List<Uuid> port1SecurityGroups, List<Uuid> port2SecurityGroups) {
379         if (port1SecurityGroups == null) {
380             return null;
381         }
382
383         if (port2SecurityGroups == null) {
384             return port1SecurityGroups;
385         }
386
387         List<Uuid> list1 = new ArrayList<>(port1SecurityGroups);
388         List<Uuid> list2 = new ArrayList<>(port2SecurityGroups);
389         for (Iterator<Uuid> iterator = list1.iterator(); iterator.hasNext();) {
390             Uuid securityGroup1 = iterator.next();
391             for (Uuid securityGroup2 : list2) {
392                 if (securityGroup1.getValue().equals(securityGroup2.getValue())) {
393                     iterator.remove();
394                     break;
395                 }
396             }
397         }
398         return list1;
399     }
400
401     private String createOfPortInterface(Port port) {
402         Interface inf = createInterface(port);
403         String infName = inf.getName();
404
405         LOG.debug("Creating OFPort Interface {}", infName);
406         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(infName);
407         try {
408             Optional<Interface> optionalInf = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
409                     interfaceIdentifier);
410             if (!optionalInf.isPresent()) {
411                 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, interfaceIdentifier, inf);
412             } else {
413                 LOG.error("Interface {} is already present", infName);
414             }
415         } catch (Exception e) {
416             LOG.error("failed to create interface {} due to the exception {} ", infName, e.getMessage());
417         }
418         return infName;
419     }
420
421     private Interface createInterface(Port port) {
422
423         String parentRefName = NeutronvpnUtils.getVifPortName(port);
424         String interfaceName = port.getUuid().getValue();
425         IfL2vlan.L2vlanMode l2VlanMode = IfL2vlan.L2vlanMode.Trunk;
426         InterfaceBuilder interfaceBuilder = new InterfaceBuilder();
427         IfL2vlanBuilder ifL2vlanBuilder = new IfL2vlanBuilder();
428         ifL2vlanBuilder.setL2vlanMode(l2VlanMode);
429         if (parentRefName != null) {
430             ParentRefsBuilder parentRefsBuilder = new ParentRefsBuilder().setParentInterface(parentRefName);
431             interfaceBuilder.addAugmentation(ParentRefs.class, parentRefsBuilder.build());
432         }
433
434         if (NeutronvpnUtils.isPortSecurityEnabled(port)) {
435             InterfaceAclBuilder interfaceAclBuilder = new InterfaceAclBuilder();
436             interfaceAclBuilder.setPortSecurityEnabled(true);
437             List<Uuid> securityGroups = port.getSecurityGroups();
438             if (securityGroups != null) {
439                 interfaceAclBuilder.setSecurityGroups(securityGroups);
440             }
441             interfaceBuilder.addAugmentation(InterfaceAcl.class, interfaceAclBuilder.build());
442         }
443
444         interfaceBuilder.setEnabled(true).setName(interfaceName).setType(L2vlan.class)
445                 .addAugmentation(IfL2vlan.class, ifL2vlanBuilder.build());
446         return interfaceBuilder.build();
447     }
448
449     private void deleteOfPortInterface(Port port) {
450         String name = port.getUuid().getValue();
451         LOG.debug("Removing OFPort Interface {}", name);
452         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(name);
453         try {
454             Optional<Interface> optionalInf = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
455                     interfaceIdentifier);
456             if (optionalInf.isPresent()) {
457                 MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, interfaceIdentifier);
458             } else {
459                 LOG.error("Interface {} is not present", name);
460             }
461         } catch (Exception e) {
462             LOG.error("Failed to delete interface {} due to the exception {}", name, e.getMessage());
463         }
464     }
465
466     private Interface updateInterface(Port original, Port update) {
467         String parentRefName = NeutronvpnUtils.getVifPortName(update);
468         String interfaceName = original.getUuid().getValue();
469         InterfaceBuilder interfaceBuilder = new InterfaceBuilder();
470
471         if (parentRefName != null) {
472             ParentRefsBuilder parentRefsBuilder = new ParentRefsBuilder().setParentInterface(parentRefName);
473             interfaceBuilder.addAugmentation(ParentRefs.class, parentRefsBuilder.build());
474         }
475
476         interfaceBuilder.setName(interfaceName);
477         return interfaceBuilder.build();
478     }
479
480     private String updateOfPortInterface(Port original, Port updated) {
481         Interface inf = updateInterface(original, updated);
482         String infName = inf.getName();
483
484         LOG.debug("Updating OFPort Interface {}", infName);
485         InstanceIdentifier interfaceIdentifier = NeutronvpnUtils.buildVlanInterfaceIdentifier(infName);
486         try {
487             Optional<Interface> optionalInf = NeutronvpnUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
488                     interfaceIdentifier);
489             if (optionalInf.isPresent()) {
490                 MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION, interfaceIdentifier, inf);
491             } else {
492                 LOG.error("Interface {} doesn't exist", infName);
493             }
494         } catch (Exception e) {
495             LOG.error("failed to update interface {} due to the exception {} ", infName, e);
496         }
497
498         return infName;
499     }
500
501     private void createElanInterface(Port port, String name) {
502         String elanInstanceName = port.getNetworkId().getValue();
503         List<PhysAddress> physAddresses = new ArrayList<>();
504         physAddresses.add(new PhysAddress(port.getMacAddress().getValue()));
505
506         InstanceIdentifier<ElanInterface> id = InstanceIdentifier.builder(ElanInterfaces.class).child(ElanInterface
507                 .class, new ElanInterfaceKey(name)).build();
508         ElanInterface elanInterface = new ElanInterfaceBuilder().setElanInstanceName(elanInstanceName)
509                 .setName(name).setStaticMacEntries(physAddresses).setKey(new ElanInterfaceKey(name)).build();
510         MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, elanInterface);
511         LOG.debug("Creating new ELan Interface {}", elanInterface);
512     }
513
514     // adds port to subnet list and creates vpnInterface
515     private Uuid addPortToSubnets(Port port) {
516         Uuid subnetId = null;
517         Uuid vpnId = null;
518         Subnetmap subnetmap = null;
519         String infName = port.getUuid().getValue();
520         boolean isLockAcquired = false;
521         String lockName = port.getUuid().getValue();
522
523         // find the subnet to which this port is associated
524         if(port.getFixedIps() == null || port.getFixedIps().isEmpty()) {
525             LOG.debug("port {} doesn't have ip", port.getName());
526             return null;
527         }
528         FixedIps ip = port.getFixedIps().get(0);
529         String ipValue = (ip.getIpAddress().getIpv4Address() != null ) ? ip.getIpAddress().getIpv4Address().getValue() :
530             ip.getIpAddress().getIpv6Address().getValue();
531         InstanceIdentifier id = NeutronvpnUtils.buildFixedIpToPortNameIdentifier(ipValue);
532         PortFixedipToPortNameBuilder builder = new PortFixedipToPortNameBuilder().setPortFixedip(ipValue)
533                 .setPortName(infName);
534         MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, id, builder.build());
535         LOG.debug("fixedIp-name map for neutron port with fixedIp: {}, name: {} added to NeutronPortData DS",
536                 ipValue, infName);
537         subnetId = ip.getSubnetId();
538         subnetmap = nvpnManager.updateSubnetNode(subnetId, null, null, null, null, null, port.getUuid());
539         if (subnetmap != null) {
540             vpnId = subnetmap.getVpnId();
541         }
542         if(vpnId != null) {
543             try {
544                 isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
545                 checkAndPublishPortAddNotification(subnetmap.getSubnetIp(), subnetId, port.getUuid());
546                 LOG.debug("Port added to subnet notification sent");
547             } catch (Exception e) {
548                 LOG.error("Port added to subnet notification failed", e);
549             } finally {
550                 if (isLockAcquired) {
551                     NeutronvpnUtils.unlock(lockManager, lockName);
552                 }
553             }
554         }
555         return vpnId;
556     }
557
558     private Uuid removePortFromSubnets(Port port) {
559         Uuid subnetId = null;
560         Uuid vpnId = null;
561         Subnetmap subnetmap = null;
562         boolean isLockAcquired = false;
563         String lockName = port.getUuid().getValue();
564
565         // find the subnet to which this port is associated
566         FixedIps ip = port.getFixedIps().get(0);
567         String ipValue = ip.getIpAddress().getIpv4Address().getValue();
568         InstanceIdentifier id = NeutronvpnUtils.buildFixedIpToPortNameIdentifier(ipValue);
569         MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, id);
570         LOG.debug("fixedIp-name map for neutron port with fixedIp: {} deleted from NeutronPortData DS", ipValue);
571         subnetId = ip.getSubnetId();
572         subnetmap = nvpnManager.removeFromSubnetNode(subnetId, null, null, null, port.getUuid());
573         if (subnetmap != null) {
574             vpnId = subnetmap.getVpnId();
575         }
576         if(vpnId != null) {
577             try {
578                 isLockAcquired = NeutronvpnUtils.lock(lockManager, lockName);
579                 checkAndPublishPortRemoveNotification(subnetmap.getSubnetIp(), subnetId, port.getUuid());
580                 LOG.debug("Port removed from subnet notification sent");
581             } catch (Exception e) {
582                 LOG.error("Port removed from subnet notification failed", e);
583             } finally {
584                 if (isLockAcquired) {
585                     NeutronvpnUtils.unlock(lockManager, lockName);
586                 }
587             }
588         }
589         return vpnId;
590     }
591
592     private void checkAndPublishPortAddNotification(String subnetIp, Uuid subnetId, Uuid portId)throws InterruptedException{
593         PortAddedToSubnetBuilder builder = new PortAddedToSubnetBuilder();
594
595         LOG.info("publish notification called");
596
597         builder.setSubnetIp(subnetIp);
598         builder.setSubnetId(subnetId);
599         builder.setPortId(portId);
600
601         notificationPublishService.putNotification(builder.build());
602     }
603
604     private void checkAndPublishPortRemoveNotification(String subnetIp, Uuid subnetId, Uuid portId)throws InterruptedException{
605         PortRemovedFromSubnetBuilder builder = new PortRemovedFromSubnetBuilder();
606
607         LOG.info("publish notification called");
608
609         builder.setPortId(portId);
610         builder.setSubnetIp(subnetIp);
611         builder.setSubnetId(subnetId);
612
613         notificationPublishService.putNotification(builder.build());
614     }
615 }