Merge "correct default prootcol handling in stateless ACL"
[netvirt.git] / vpnservice / elanmanager / elanmanager-impl / src / main / java / org / opendaylight / netvirt / elan / internal / ElanServiceProvider.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
9 package org.opendaylight.netvirt.elan.internal;
10
11 import com.google.common.base.Optional;
12 import java.math.BigInteger;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.HashSet;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Set;
20 import java.util.concurrent.Future;
21 import java.util.function.BiFunction;
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
24 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.genius.interfacemanager.exceptions.InterfaceAlreadyExistsException;
27 import org.opendaylight.genius.interfacemanager.globals.IfmConstants;
28 import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
29 import org.opendaylight.genius.mdsalutil.MDSALUtil;
30 import org.opendaylight.genius.utils.clustering.EntityOwnerUtils;
31 import org.opendaylight.genius.utils.hwvtep.HwvtepSouthboundConstants;
32 import org.opendaylight.netvirt.elan.statusanddiag.ElanStatusMonitor;
33 import org.opendaylight.netvirt.elan.utils.ElanConstants;
34 import org.opendaylight.netvirt.elan.utils.ElanUtils;
35 import org.opendaylight.netvirt.elanmanager.api.IElanService;
36 import org.opendaylight.netvirt.elanmanager.exceptions.MacNotFoundException;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInputBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlan;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstance;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInstanceBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterface.EtreeInterfaceType;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.etree.rev160614.EtreeInterfaceBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInterfaces;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan._interface.forwarding.entries.ElanInterfaceMac;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.dpn.interfaces.elan.dpn.interfaces.list.DpnInterfaces;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterface;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.interfaces.ElanInterfaceKey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.state.Elan;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.forwarding.entries.MacEntry;
62 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
63 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
64 import org.opendaylight.yangtools.yang.common.RpcResult;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 public class ElanServiceProvider implements IElanService {
69
70     private static final Logger LOG = LoggerFactory.getLogger(ElanServiceProvider.class);
71
72     private final IdManagerService idManager;
73     private final IInterfaceManager interfaceManager;
74     private final ElanInstanceManager elanInstanceManager;
75     private final ElanBridgeManager bridgeMgr;
76     private final DataBroker broker;
77     private final ElanStatusMonitor elanStatusMonitor;
78     private static ElanUtils elanUtils;
79
80     private boolean generateIntBridgeMac = true;
81
82     public ElanServiceProvider(IdManagerService idManager, IInterfaceManager interfaceManager,
83                                ElanInstanceManager elanInstanceManager, ElanBridgeManager bridgeMgr,
84                                DataBroker dataBroker,
85                                ElanInterfaceManager elanInterfaceManager,
86                                ElanStatusMonitor elanStatusMonitor, ElanUtils elanUtils,
87                                EntityOwnershipService entityOwnershipService) {
88         this.idManager = idManager;
89         this.interfaceManager = interfaceManager;
90         this.elanInstanceManager = elanInstanceManager;
91         this.bridgeMgr = bridgeMgr;
92         this.broker = dataBroker;
93         this.elanStatusMonitor = elanStatusMonitor;
94         this.elanUtils = elanUtils;
95         elanInterfaceManager.setElanUtils(elanUtils);
96         try {
97             EntityOwnerUtils.registerEntityCandidateForOwnerShip(entityOwnershipService,
98                     HwvtepSouthboundConstants.ELAN_ENTITY_TYPE, HwvtepSouthboundConstants.ELAN_ENTITY_TYPE,
99                     null/*listener*/);
100         } catch (CandidateAlreadyRegisteredException e) {
101             LOG.error("failed to register the entity");
102         }
103     }
104
105     @SuppressWarnings("checkstyle:IllegalCatch")
106     public void init() throws Exception {
107         LOG.info("Starting ElnaServiceProvider");
108         elanStatusMonitor.reportStatus("STARTING");
109         try {
110             createIdPool();
111             elanStatusMonitor.reportStatus("OPERATIONAL");
112         } catch (Exception e) {
113             elanStatusMonitor.reportStatus("ERROR");
114             throw e;
115         }
116     }
117
118     private void createIdPool() throws Exception {
119         CreateIdPoolInput createPool = new CreateIdPoolInputBuilder().setPoolName(ElanConstants.ELAN_ID_POOL_NAME)
120                 .setLow(ElanConstants.ELAN_ID_LOW_VALUE).setHigh(ElanConstants.ELAN_ID_HIGH_VALUE).build();
121         Future<RpcResult<Void>> result = idManager.createIdPool(createPool);
122         if (result != null && result.get().isSuccessful()) {
123             LOG.debug("ELAN Id Pool is created successfully");
124         }
125     }
126
127     @Override
128     public boolean createElanInstance(String elanInstanceName, long macTimeout, String description) {
129         ElanInstance existingElanInstance = elanInstanceManager.getElanInstanceByName(elanInstanceName);
130         boolean isSuccess = true;
131         if (existingElanInstance != null) {
132             if (compareWithExistingElanInstance(existingElanInstance, macTimeout, description)) {
133                 LOG.debug("Elan Instance is already present in the Operational DS {}", existingElanInstance);
134                 return true;
135             } else {
136                 ElanInstance updateElanInstance = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
137                         .setDescription(description).setMacTimeout(macTimeout)
138                         .setKey(new ElanInstanceKey(elanInstanceName)).build();
139                 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION,
140                         ElanUtils.getElanInstanceConfigurationDataPath(elanInstanceName), updateElanInstance);
141                 LOG.debug("Updating the Elan Instance {} with MAC TIME-OUT %l and Description %s ",
142                         updateElanInstance, macTimeout, description);
143             }
144         } else {
145             ElanInstance elanInstance = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
146                     .setMacTimeout(macTimeout).setDescription(description).setKey(new ElanInstanceKey(elanInstanceName))
147                     .build();
148             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION,
149                     ElanUtils.getElanInstanceConfigurationDataPath(elanInstanceName), elanInstance);
150             LOG.debug("Creating the new Elan Instance {}", elanInstance);
151         }
152         return isSuccess;
153     }
154
155     @Override
156     public boolean createEtreeInstance(String elanInstanceName, long macTimeout, String description) {
157         ElanInstance existingElanInstance = elanInstanceManager.getElanInstanceByName(elanInstanceName);
158         boolean isSuccess = true;
159         if (existingElanInstance != null) {
160             if (compareWithExistingElanInstance(existingElanInstance, macTimeout, description)) {
161                 LOG.warn("Etree Instance is already present in the Operational DS {}", existingElanInstance);
162                 return true;
163             } else {
164                 EtreeInstance etreeInstance = new EtreeInstanceBuilder().build();
165                 ElanInstance updateElanInstance = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
166                         .setDescription(description).setMacTimeout(macTimeout)
167                         .setKey(new ElanInstanceKey(elanInstanceName))
168                         .addAugmentation(EtreeInstance.class, etreeInstance).build();
169                 MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION,
170                         ElanUtils.getElanInstanceConfigurationDataPath(elanInstanceName), updateElanInstance);
171                 LOG.debug("Updating the Etree Instance {} with MAC TIME-OUT %l and Description %s ",
172                         updateElanInstance, macTimeout, description);
173             }
174         } else {
175             EtreeInstance etreeInstance = new EtreeInstanceBuilder().build();
176             ElanInstance elanInstance = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName)
177                     .setMacTimeout(macTimeout).setDescription(description).setKey(new ElanInstanceKey(elanInstanceName))
178                     .addAugmentation(EtreeInstance.class, etreeInstance).build();
179             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION,
180                     ElanUtils.getElanInstanceConfigurationDataPath(elanInstanceName), elanInstance);
181             LOG.debug("Creating the new Etree Instance {}", elanInstance);
182         }
183         return isSuccess;
184     }
185
186     @Override
187     public EtreeInterface getEtreeInterfaceByElanInterfaceName(String elanInterface) {
188         return ElanUtils.getEtreeInterfaceByElanInterfaceName(broker, elanInterface);
189     }
190
191     public static boolean compareWithExistingElanInstance(ElanInstance existingElanInstance, long macTimeOut,
192             String description) {
193         boolean isEqual = false;
194         if (existingElanInstance.getMacTimeout() == macTimeOut
195                 && existingElanInstance.getDescription().equals(description)) {
196             isEqual = true;
197         }
198         return isEqual;
199     }
200
201     @Override
202     public void updateElanInstance(String elanInstanceName, long newMacTimout, String newDescription) {
203         createElanInstance(elanInstanceName, newMacTimout, newDescription);
204     }
205
206     @Override
207     public boolean deleteEtreeInstance(String etreeInstanceName) {
208         return deleteElanInstance(etreeInstanceName);
209     }
210
211     @Override
212     public boolean deleteElanInstance(String elanInstanceName) {
213         boolean isSuccess = false;
214         ElanInstance existingElanInstance = elanInstanceManager.getElanInstanceByName(elanInstanceName);
215         if (existingElanInstance == null) {
216             LOG.debug("Elan Instance is not present {}", existingElanInstance);
217             return isSuccess;
218         }
219         LOG.debug("Deletion of the existing Elan Instance {}", existingElanInstance);
220         ElanUtils.delete(broker, LogicalDatastoreType.CONFIGURATION,
221                 ElanUtils.getElanInstanceConfigurationDataPath(elanInstanceName));
222         isSuccess = true;
223         return isSuccess;
224     }
225
226     @Override
227     public void addEtreeInterface(String etreeInstanceName, String interfaceName, EtreeInterfaceType interfaceType,
228             List<String> staticMacAddresses, String description) {
229         ElanInstance existingElanInstance = elanInstanceManager.getElanInstanceByName(etreeInstanceName);
230         if (existingElanInstance != null && existingElanInstance.getAugmentation(EtreeInstance.class) != null) {
231             EtreeInterface etreeInterface = new EtreeInterfaceBuilder().setEtreeInterfaceType(interfaceType).build();
232             ElanInterface elanInterface;
233             if (staticMacAddresses == null) {
234                 elanInterface = new ElanInterfaceBuilder().setElanInstanceName(etreeInstanceName)
235                         .setDescription(description).setName(interfaceName).setKey(new ElanInterfaceKey(interfaceName))
236                         .addAugmentation(EtreeInterface.class, etreeInterface).build();
237             } else {
238                 elanInterface = new ElanInterfaceBuilder().setElanInstanceName(etreeInstanceName)
239                         .setDescription(description).setName(interfaceName)
240                         .setStaticMacEntries(getPhysAddress(staticMacAddresses))
241                         .setKey(new ElanInterfaceKey(interfaceName))
242                         .addAugmentation(EtreeInterface.class, etreeInterface).build();
243             }
244             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION,
245                     ElanUtils.getElanInterfaceConfigurationDataPathId(interfaceName), elanInterface);
246             LOG.debug("Creating the new Etree Interface {}", elanInterface);
247         }
248     }
249
250     @Override
251     public void addElanInterface(String elanInstanceName, String interfaceName, List<String> staticMacAddresses,
252             String description) {
253         ElanInstance existingElanInstance = elanInstanceManager.getElanInstanceByName(elanInstanceName);
254         if (existingElanInstance != null) {
255             ElanInterface elanInterface;
256             if (staticMacAddresses == null) {
257                 elanInterface = new ElanInterfaceBuilder().setElanInstanceName(elanInstanceName)
258                         .setDescription(description).setName(interfaceName).setKey(new ElanInterfaceKey(interfaceName))
259                         .build();
260             } else {
261                 elanInterface = new ElanInterfaceBuilder().setElanInstanceName(elanInstanceName)
262                         .setDescription(description).setName(interfaceName)
263                         .setStaticMacEntries(getPhysAddress(staticMacAddresses))
264                         .setKey(new ElanInterfaceKey(interfaceName)).build();
265             }
266             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION,
267                     ElanUtils.getElanInterfaceConfigurationDataPathId(interfaceName), elanInterface);
268             LOG.debug("Creating the new ELan Interface {}", elanInterface);
269         }
270     }
271
272     @Override
273     public void updateElanInterface(String elanInstanceName, String interfaceName,
274             List<String> updatedStaticMacAddresses, String newDescription) {
275         ElanInterface existingElanInterface = ElanUtils.getElanInterfaceByElanInterfaceName(broker, interfaceName);
276         if (existingElanInterface == null) {
277             return;
278         }
279         List<PhysAddress> existingMacAddress = existingElanInterface.getStaticMacEntries();
280         List<PhysAddress> updatedMacAddresses = getPhysAddress(updatedStaticMacAddresses);
281         List<PhysAddress> updatedPhysAddress = getUpdatedPhyAddress(existingMacAddress, updatedMacAddresses);
282         if (updatedPhysAddress.size() > 0) {
283             LOG.debug("updating the ElanInterface with new Mac Entries {}", updatedStaticMacAddresses);
284             ElanInterface elanInterface = new ElanInterfaceBuilder().setElanInstanceName(elanInstanceName)
285                     .setName(interfaceName).setDescription(newDescription).setStaticMacEntries(updatedPhysAddress)
286                     .setKey(new ElanInterfaceKey(interfaceName)).build();
287             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION,
288                     ElanUtils.getElanInterfaceConfigurationDataPathId(interfaceName), elanInterface);
289         }
290     }
291
292     @Override
293     public void deleteEtreeInterface(String elanInstanceName, String interfaceName) {
294         deleteElanInterface(elanInstanceName, interfaceName);
295         LOG.debug("deleting the Etree Interface {}", interfaceName);
296     }
297
298     @Override
299     public void deleteElanInterface(String elanInstanceName, String interfaceName) {
300         ElanInterface existingElanInterface = ElanUtils.getElanInterfaceByElanInterfaceName(broker, interfaceName);
301         if (existingElanInterface != null) {
302             ElanUtils.delete(broker, LogicalDatastoreType.CONFIGURATION,
303                     ElanUtils.getElanInterfaceConfigurationDataPathId(interfaceName));
304             LOG.debug("deleting the Elan Interface {}", existingElanInterface);
305         }
306     }
307
308     @Override
309     public void addStaticMacAddress(String elanInstanceName, String interfaceName, String macAddress) {
310         ElanInterface existingElanInterface = ElanUtils.getElanInterfaceByElanInterfaceName(broker, interfaceName);
311         PhysAddress updateStaticMacAddress = new PhysAddress(macAddress);
312         if (existingElanInterface != null) {
313             List<PhysAddress> existingMacAddress = existingElanInterface.getStaticMacEntries();
314             if (existingMacAddress.contains(updateStaticMacAddress)) {
315                 return;
316             }
317             existingMacAddress.add(updateStaticMacAddress);
318             ElanInterface elanInterface = new ElanInterfaceBuilder().setElanInstanceName(elanInstanceName)
319                     .setName(interfaceName).setStaticMacEntries(existingMacAddress)
320                     .setDescription(existingElanInterface.getDescription()).setKey(new ElanInterfaceKey(interfaceName))
321                     .build();
322             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION,
323                     ElanUtils.getElanInterfaceConfigurationDataPathId(interfaceName), elanInterface);
324         }
325     }
326
327     @Override
328     public void deleteStaticMacAddress(String elanInstanceName, String interfaceName, String macAddress)
329             throws MacNotFoundException {
330         ElanInterface existingElanInterface = ElanUtils.getElanInterfaceByElanInterfaceName(broker, interfaceName);
331         PhysAddress physAddress = new PhysAddress(macAddress);
332         if (existingElanInterface == null) {
333             return;
334         }
335         List<PhysAddress> existingMacAddress = existingElanInterface.getStaticMacEntries();
336         if (existingMacAddress.contains(physAddress)) {
337             existingMacAddress.remove(physAddress);
338             ElanInterface elanInterface = new ElanInterfaceBuilder().setElanInstanceName(elanInstanceName)
339                     .setName(interfaceName).setStaticMacEntries(existingMacAddress)
340                     .setDescription(existingElanInterface.getDescription()).setKey(new ElanInterfaceKey(interfaceName))
341                     .build();
342             MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION,
343                     ElanUtils.getElanInterfaceConfigurationDataPathId(interfaceName), elanInterface);
344         } else {
345             throw new MacNotFoundException("deleteStaticMacAddress did not find MAC: " + macAddress);
346         }
347     }
348
349     @Override
350     public Collection<MacEntry> getElanMacTable(String elanInstanceName) {
351         Elan elanInfo = ElanUtils.getElanByName(broker, elanInstanceName);
352         List<MacEntry> macAddress = new ArrayList<>();
353         if (elanInfo == null) {
354             return macAddress;
355         }
356         List<String> elanInterfaces = elanInfo.getElanInterfaces();
357         if (elanInterfaces != null && elanInterfaces.size() > 0) {
358             for (String elanInterface : elanInterfaces) {
359                 ElanInterfaceMac elanInterfaceMac = elanUtils.getElanInterfaceMacByInterfaceName(elanInterface);
360                 if (elanInterfaceMac != null && elanInterfaceMac.getMacEntry() != null
361                         && elanInterfaceMac.getMacEntry().size() > 0) {
362                     macAddress.addAll(elanInterfaceMac.getMacEntry());
363                 }
364             }
365         }
366         return macAddress;
367     }
368
369     @Override
370     public void flushMACTable(String elanInstanceName) {
371         Elan elanInfo = ElanUtils.getElanByName(broker, elanInstanceName);
372         if (elanInfo == null) {
373             return;
374         }
375         List<String> elanInterfaces = elanInfo.getElanInterfaces();
376         if (elanInterfaces == null || elanInterfaces.isEmpty()) {
377             return;
378         }
379         for (String elanInterface : elanInterfaces) {
380             ElanInterfaceMac elanInterfaceMac = elanUtils.getElanInterfaceMacByInterfaceName(elanInterface);
381             if (elanInterfaceMac.getMacEntry() != null && elanInterfaceMac.getMacEntry().size() > 0) {
382                 List<MacEntry> macEntries = elanInterfaceMac.getMacEntry();
383                 for (MacEntry macEntry : macEntries) {
384                     try {
385                         deleteStaticMacAddress(elanInstanceName, elanInterface, macEntry.getMacAddress().getValue());
386                     } catch (MacNotFoundException e) {
387                         LOG.error("Mac Not Found Exception {}", e);
388                     }
389                 }
390             }
391         }
392
393     }
394
395     public static List<PhysAddress> getPhysAddress(List<String> macAddress) {
396         List<PhysAddress> physAddresses = new ArrayList<>();
397         for (String mac : macAddress) {
398             physAddresses.add(new PhysAddress(mac));
399         }
400         return physAddresses;
401     }
402
403     public List<PhysAddress> getUpdatedPhyAddress(List<PhysAddress> originalAddresses,
404             List<PhysAddress> updatePhyAddresses) {
405         if (updatePhyAddresses != null && !updatePhyAddresses.isEmpty()) {
406             List<PhysAddress> existingClonedPhyAddress = new ArrayList<>();
407             if (originalAddresses != null && !originalAddresses.isEmpty()) {
408                 existingClonedPhyAddress.addAll(0, originalAddresses);
409                 originalAddresses.removeAll(updatePhyAddresses);
410                 updatePhyAddresses.removeAll(existingClonedPhyAddress);
411             }
412         }
413         return updatePhyAddresses;
414     }
415
416     @Override
417     public ElanInstance getElanInstance(String elanName) {
418         return ElanUtils.getElanInstanceByName(broker, elanName);
419     }
420
421     @Override
422     public List<ElanInstance> getElanInstances() {
423         List<ElanInstance> elanList = new ArrayList<>();
424         InstanceIdentifier<ElanInstances> elanInstancesIdentifier = InstanceIdentifier.builder(ElanInstances.class)
425                 .build();
426         Optional<ElanInstances> elansOptional = elanUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
427                 elanInstancesIdentifier);
428         if (elansOptional.isPresent()) {
429             elanList.addAll(elansOptional.get().getElanInstance());
430         }
431         return elanList;
432     }
433
434     @Override
435     public List<String> getElanInterfaces(String elanInstanceName) {
436         List<String> elanInterfaces = new ArrayList<>();
437         InstanceIdentifier<ElanInterfaces> elanInterfacesIdentifier = InstanceIdentifier.builder(ElanInterfaces.class)
438                 .build();
439         Optional<ElanInterfaces> elanInterfacesOptional = elanUtils.read(broker, LogicalDatastoreType.CONFIGURATION,
440                 elanInterfacesIdentifier);
441         if (!elanInterfacesOptional.isPresent()) {
442             return elanInterfaces;
443         }
444         List<ElanInterface> elanInterfaceList = elanInterfacesOptional.get().getElanInterface();
445         for (ElanInterface elanInterface : elanInterfaceList) {
446             if (elanInterface.getElanInstanceName().equals(elanInstanceName)) {
447                 elanInterfaces.add(elanInterface.getName());
448             }
449         }
450         return elanInterfaces;
451     }
452
453     public boolean getGenerateIntBridgeMac() {
454         return generateIntBridgeMac;
455     }
456
457     public void setGenerateIntBridgeMac(boolean generateIntBridgeMac) {
458         this.generateIntBridgeMac = generateIntBridgeMac;
459     }
460
461     @Override
462     public void createExternalElanNetworks(Node node) {
463         handleExternalElanNetworks(node, (elanInstance, interfaceName) -> {
464             createExternalElanNetwork(elanInstance, interfaceName);
465             return null;
466         });
467     }
468
469     @Override
470     public void createExternalElanNetwork(ElanInstance elanInstance) {
471         handleExternalElanNetwork(elanInstance, (elanInstance1, interfaceName) -> {
472             createExternalElanNetwork(elanInstance1, interfaceName);
473             return null;
474         });
475     }
476
477     private void createExternalElanNetwork(ElanInstance elanInstance, String interfaceName) {
478         if (interfaceName == null) {
479             LOG.trace("No physial interface is attached to {}", elanInstance.getPhysicalNetworkName());
480             return;
481         }
482
483         String elanInterfaceName = createIetfInterfaces(elanInstance, interfaceName);
484         addElanInterface(elanInstance.getElanInstanceName(), elanInterfaceName, null, null);
485     }
486
487     @Override
488     public void deleteExternalElanNetworks(Node node) {
489         handleExternalElanNetworks(node, (elanInstance, interfaceName) -> {
490             deleteExternalElanNetwork(elanInstance, interfaceName);
491             return null;
492         });
493     }
494
495     @Override
496     public void deleteExternalElanNetwork(ElanInstance elanInstance) {
497         handleExternalElanNetwork(elanInstance, (elanInstance1, interfaceName) -> {
498             deleteExternalElanNetwork(elanInstance1, interfaceName);
499             return null;
500         });
501     }
502
503     private void deleteExternalElanNetwork(ElanInstance elanInstance, String interfaceName) {
504         if (interfaceName == null) {
505             LOG.trace("No physial interface is attached to {}", elanInstance.getPhysicalNetworkName());
506             return;
507         }
508
509         String elanInstanceName = elanInstance.getElanInstanceName();
510         for (String elanInterface : getExternalElanInterfaces(elanInstanceName)) {
511             if (elanInterface.startsWith(interfaceName)) {
512                 deleteIetfInterface(elanInterface);
513                 deleteElanInterface(elanInstanceName, elanInterface);
514             }
515         }
516     }
517
518     @Override
519     public void updateExternalElanNetworks(Node origNode, Node updatedNode) {
520         if (!bridgeMgr.isIntegrationBridge(updatedNode)) {
521             return;
522         }
523
524         List<ElanInstance> elanInstances = getElanInstances();
525         if (elanInstances == null || elanInstances.isEmpty()) {
526             LOG.trace("No ELAN instances found");
527             return;
528         }
529
530         Optional<Map<String, String>> origProviderMapOpt = bridgeMgr.getOpenvswitchOtherConfigMap(origNode,
531                 ElanBridgeManager.PROVIDER_MAPPINGS_KEY);
532         Optional<Map<String, String>> updatedProviderMapOpt = bridgeMgr.getOpenvswitchOtherConfigMap(updatedNode,
533                 ElanBridgeManager.PROVIDER_MAPPINGS_KEY);
534         Map<String, String> origProviderMappping = origProviderMapOpt.or(Collections.emptyMap());
535         Map<String, String> updatedProviderMappping = updatedProviderMapOpt.or(Collections.emptyMap());
536
537         for (ElanInstance elanInstance : elanInstances) {
538             String physicalNetworkName = elanInstance.getPhysicalNetworkName();
539             if (physicalNetworkName != null) {
540                 String origPortName = origProviderMappping.get(physicalNetworkName);
541                 String updatedPortName = updatedProviderMappping.get(physicalNetworkName);
542                 if (origPortName != null && !origPortName.equals(updatedPortName)) {
543                     deleteExternalElanNetwork(elanInstance, getExtInterfaceName(origNode, physicalNetworkName));
544                 }
545                 if (updatedPortName != null && !updatedPortName.equals(origPortName)) {
546                     createExternalElanNetwork(elanInstance, getExtInterfaceName(updatedNode, updatedPortName));
547                 }
548             }
549         }
550     }
551
552     @Override
553     public String getExternalElanInterface(String elanInstanceName, BigInteger dpnId) {
554         DpnInterfaces dpnInterfaces = elanUtils.getElanInterfaceInfoByElanDpn(elanInstanceName, dpnId);
555         if (dpnInterfaces == null || dpnInterfaces.getInterfaces() == null) {
556             LOG.trace("Elan {} does not have interfaces in DPN {}", elanInstanceName, dpnId);
557             return null;
558         }
559
560         for (String dpnInterface : dpnInterfaces.getInterfaces()) {
561             if (elanUtils.isExternal(dpnInterface)) {
562                 return dpnInterface;
563             }
564         }
565
566         LOG.trace("Elan {} does not have any external interace attached to DPN {}", elanInstanceName, dpnId);
567         return null;
568     }
569
570     @Override
571     public Collection<String> getExternalElanInterfaces(String elanInstanceName) {
572         List<String> elanInterfaces = getElanInterfaces(elanInstanceName);
573         if (elanInterfaces == null || elanInterfaces.isEmpty()) {
574             LOG.trace("No ELAN interfaces defined for {}", elanInstanceName);
575             return Collections.emptySet();
576         }
577
578         Set<String> externalElanInterfaces = new HashSet<>();
579         for (String elanInterface : elanInterfaces) {
580             if (elanUtils.isExternal(elanInterface)) {
581                 externalElanInterfaces.add(elanInterface);
582             }
583         }
584
585         return externalElanInterfaces;
586     }
587
588     @Override
589     public boolean isExternalInterface(String interfaceName) {
590         return elanUtils.isExternal(interfaceName);
591     }
592
593     @Override
594     public ElanInterface getElanInterfaceByElanInterfaceName(String interfaceName) {
595         return ElanUtils.getElanInterfaceByElanInterfaceName(broker, interfaceName);
596     }
597
598     /**
599      * Create ietf-interfaces based on the ELAN segment type.<br>
600      * For segment type flat - create transparent interface pointing to the
601      * patch-port attached to the physnet port.<br>
602      * For segment type vlan - create trunk interface pointing to the patch-port
603      * attached to the physnet port + trunk-member interface pointing to the
604      * trunk interface.
605      *
606      * @param elanInstance
607      *            ELAN instance
608      * @param parentRef
609      *            parent interface name
610      * @return the name of the interface to be added to the ELAN instance i.e.
611      *         trunk-member name for vlan network and transparent for flat
612      *         network or null otherwise
613      */
614     private String createIetfInterfaces(ElanInstance elanInstance, String parentRef) {
615         String interfaceName = null;
616
617         try {
618             if (ElanUtils.isFlat(elanInstance)) {
619                 interfaceName = parentRef + IfmConstants.OF_URI_SEPARATOR + "flat";
620                 interfaceManager.createVLANInterface(interfaceName, parentRef, null, null, null,
621                         IfL2vlan.L2vlanMode.Transparent, true);
622             } else if (ElanUtils.isVlan(elanInstance)) {
623                 Long segmentationId = elanInstance.getSegmentationId();
624                 interfaceName = parentRef + IfmConstants.OF_URI_SEPARATOR + segmentationId;
625                 String trunkName = parentRef + IfmConstants.OF_URI_SEPARATOR + "trunk";
626                 // trunk interface may have been created by other vlan network
627                 Interface trunkInterface = ElanUtils.getInterfaceFromConfigDS(trunkName, broker);
628                 if (trunkInterface == null) {
629                     interfaceManager.createVLANInterface(trunkName, parentRef, null, null, null,
630                             IfL2vlan.L2vlanMode.Trunk, true);
631                 }
632                 interfaceManager.createVLANInterface(interfaceName, trunkName, null, segmentationId.intValue(), null,
633                         IfL2vlan.L2vlanMode.TrunkMember, true);
634             }
635         } catch (InterfaceAlreadyExistsException e) {
636             LOG.trace("Interface {} was already created", interfaceName);
637         }
638
639         return interfaceName;
640     }
641
642     private void deleteIetfInterface(String interfaceName) {
643         InterfaceKey interfaceKey = new InterfaceKey(interfaceName);
644         InstanceIdentifier<Interface> interfaceInstanceIdentifier = InstanceIdentifier.builder(Interfaces.class)
645                 .child(Interface.class, interfaceKey).build();
646         MDSALUtil.syncDelete(broker, LogicalDatastoreType.CONFIGURATION, interfaceInstanceIdentifier);
647         LOG.debug("Deleting IETF interface {}", interfaceName);
648     }
649
650     private String getExtInterfaceName(Node node, String physicalNetworkName) {
651         if (physicalNetworkName == null) {
652             return null;
653         }
654
655         String providerMappingValue = bridgeMgr.getProviderMappingValue(node, physicalNetworkName);
656         if (providerMappingValue == null) {
657             LOG.trace("No provider mapping found for physicalNetworkName {} node {}", physicalNetworkName,
658                     node.getNodeId().getValue());
659             return null;
660         }
661
662         return bridgeMgr.southboundUtils.getDataPathId(node) + IfmConstants.OF_URI_SEPARATOR
663                 + bridgeMgr.getIntBridgePortNameFor(node, providerMappingValue);
664     }
665
666     private void handleExternalElanNetworks(Node node, BiFunction<ElanInstance, String, Void> function) {
667         if (!bridgeMgr.isIntegrationBridge(node)) {
668             return;
669         }
670
671         List<ElanInstance> elanInstances = getElanInstances();
672         if (elanInstances == null || elanInstances.isEmpty()) {
673             LOG.trace("No ELAN instances found");
674             return;
675         }
676
677         for (ElanInstance elanInstance : elanInstances) {
678             String interfaceName = getExtInterfaceName(node, elanInstance.getPhysicalNetworkName());
679             if (interfaceName != null) {
680                 function.apply(elanInstance, interfaceName);
681             }
682         }
683     }
684
685     private void handleExternalElanNetwork(ElanInstance elanInstance, BiFunction<ElanInstance, String, Void> function) {
686         String elanInstanceName = elanInstance.getElanInstanceName();
687         if (elanInstance.getPhysicalNetworkName() == null) {
688             LOG.trace("No physical network attached to {}", elanInstanceName);
689             return;
690         }
691
692         List<Node> nodes = bridgeMgr.southboundUtils.getOvsdbNodes();
693         if (nodes == null || nodes.isEmpty()) {
694             LOG.trace("No OVS nodes found while creating external network for ELAN {}",
695                     elanInstance.getElanInstanceName());
696             return;
697         }
698
699         for (Node node : nodes) {
700             if (bridgeMgr.isIntegrationBridge(node)) {
701                 String interfaceName = getExtInterfaceName(node, elanInstance.getPhysicalNetworkName());
702                 function.apply(elanInstance, interfaceName);
703             }
704         }
705     }
706
707 }