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