bug 7599 performance improvement for ucast macs
[ovsdb.git] / hwvtepsouthbound / hwvtepsouthbound-impl / src / main / java / org / opendaylight / ovsdb / hwvtepsouthbound / HwvtepConnectionManager.java
1 /*
2  * Copyright (c) 2015 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.ovsdb.hwvtepsouthbound;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
17 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
18 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
19 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
20 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
21 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
22 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
23 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
24 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
25 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
26 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
29 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.ReconciliationManager;
30 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.ReconciliationTask;
31 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.configuration.HwvtepReconciliationTask;
32 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.connection.ConnectionReconciliationTask;
33 import org.opendaylight.ovsdb.hwvtepsouthbound.transact.DependencyQueue;
34 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.HwvtepGlobalRemoveCommand;
35 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionCommand;
36 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvoker;
37 import org.opendaylight.ovsdb.lib.OvsdbClient;
38 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
39 import org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService;
40 import org.opendaylight.ovsdb.lib.operations.Operation;
41 import org.opendaylight.ovsdb.lib.operations.OperationResult;
42 import org.opendaylight.ovsdb.lib.operations.Select;
43 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
44 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
45 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
46 import org.opendaylight.ovsdb.schema.hardwarevtep.Global;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalSwitchAttributes;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.PhysicalSwitchAugmentation;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ConnectionInfo;
51 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
52 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 import javax.annotation.Nonnull;
58 import javax.annotation.Nullable;
59 import java.net.ConnectException;
60 import java.net.InetAddress;
61 import java.net.UnknownHostException;
62 import java.util.ArrayList;
63 import java.util.List;
64 import java.util.Map;
65 import java.util.concurrent.ConcurrentHashMap;
66 import java.util.concurrent.ExecutionException;
67 import java.util.concurrent.TimeUnit;
68 import java.util.concurrent.TimeoutException;
69
70 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
71
72 public class HwvtepConnectionManager implements OvsdbConnectionListener, AutoCloseable{
73     private Map<ConnectionInfo, HwvtepConnectionInstance> clients = new ConcurrentHashMap<>();
74     private static final Logger LOG = LoggerFactory.getLogger(HwvtepConnectionManager.class);
75     private static final String ENTITY_TYPE = "hwvtep";
76     private static final int DB_FETCH_TIMEOUT = 1000;
77
78     private DataBroker db;
79     private TransactionInvoker txInvoker;
80     private Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers = new ConcurrentHashMap<>();
81     private Map<Entity, HwvtepConnectionInstance> entityConnectionMap = new ConcurrentHashMap<>();
82     private EntityOwnershipService entityOwnershipService;
83     private HwvtepDeviceEntityOwnershipListener hwvtepDeviceEntityOwnershipListener;
84     private final ReconciliationManager reconciliationManager;
85
86     public HwvtepConnectionManager(DataBroker db, TransactionInvoker txInvoker,
87                     EntityOwnershipService entityOwnershipService) {
88         this.db = db;
89         this.txInvoker = txInvoker;
90         this.entityOwnershipService = entityOwnershipService;
91         this.hwvtepDeviceEntityOwnershipListener = new HwvtepDeviceEntityOwnershipListener(this,entityOwnershipService);
92         this.reconciliationManager = new ReconciliationManager(db);
93     }
94
95     @Override
96     public void close() throws Exception {
97         if (hwvtepDeviceEntityOwnershipListener != null) {
98             hwvtepDeviceEntityOwnershipListener.close();
99         }
100
101         for (HwvtepConnectionInstance client: clients.values()) {
102             client.disconnect();
103         }
104         DependencyQueue.close();
105     }
106
107     @Override
108     public void connected(@Nonnull final OvsdbClient externalClient) {
109         LOG.info("Library connected {} from {}:{} to {}:{}",
110                 externalClient.getConnectionInfo().getType(),
111                 externalClient.getConnectionInfo().getRemoteAddress(),
112                 externalClient.getConnectionInfo().getRemotePort(),
113                 externalClient.getConnectionInfo().getLocalAddress(),
114                 externalClient.getConnectionInfo().getLocalPort());
115         List<String> databases = new ArrayList<>();
116         try {
117             databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
118             if(databases.contains(HwvtepSchemaConstants.HARDWARE_VTEP)) {
119                 HwvtepConnectionInstance hwClient = connectedButCallBacksNotRegistered(externalClient);
120                 registerEntityForOwnership(hwClient);
121             }
122         } catch (InterruptedException | ExecutionException | TimeoutException e) {
123             LOG.warn("Unable to fetch Database list from device {}. Disconnecting from the device.",
124                     externalClient.getConnectionInfo().getRemoteAddress(), e);
125             externalClient.disconnect();
126         }
127     }
128
129     @Override
130     public void disconnected(OvsdbClient client) {
131         LOG.info("Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
132                 client.getConnectionInfo().getType(),
133                 client.getConnectionInfo().getRemoteAddress(),
134                 client.getConnectionInfo().getRemotePort(),
135                 client.getConnectionInfo().getLocalAddress(),
136                 client.getConnectionInfo().getLocalPort());
137         ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(client);
138         HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
139         if (hwvtepConnectionInstance != null) {
140             // Unregister Entity ownership as soon as possible ,so this instance should
141             // not be used as a candidate in Entity election (given that this instance is
142             // about to disconnect as well), if current owner get disconnected from
143             // HWVTEP device.
144             unregisterEntityForOwnership(hwvtepConnectionInstance);
145
146             //TODO: remove all the hwvtep nodes
147             txInvoker.invoke(new HwvtepGlobalRemoveCommand(hwvtepConnectionInstance, null, null));
148
149             removeConnectionInstance(key);
150
151             //Controller initiated connection can be terminated from switch side.
152             //So cleanup the instance identifier cache.
153             removeInstanceIdentifier(key);
154             retryConnection(hwvtepConnectionInstance.getInstanceIdentifier(),
155                     hwvtepConnectionInstance.getHwvtepGlobalAugmentation(),
156                     ConnectionReconciliationTriggers.ON_DISCONNECT);
157         } else {
158             LOG.warn("HWVTEP disconnected event did not find connection instance for {}", key);
159         }
160         LOG.trace("HwvtepConnectionManager exit disconnected client: {}", client);
161     }
162
163     public OvsdbClient connect(InstanceIdentifier<Node> iid,
164                                HwvtepGlobalAugmentation hwvtepGlobal) throws UnknownHostException, ConnectException {
165         LOG.info("Connecting to {}", HwvtepSouthboundUtil.connectionInfoToString(hwvtepGlobal.getConnectionInfo()));
166         InetAddress ip = HwvtepSouthboundMapper.createInetAddress(hwvtepGlobal.getConnectionInfo().getRemoteIp());
167         OvsdbClient client = OvsdbConnectionService.getService()
168                         .connect(ip, hwvtepGlobal.getConnectionInfo().getRemotePort().getValue());
169         if(client != null) {
170             putInstanceIdentifier(hwvtepGlobal.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
171             HwvtepConnectionInstance hwvtepConnectionInstance = connectedButCallBacksNotRegistered(client);
172             hwvtepConnectionInstance.setHwvtepGlobalAugmentation(hwvtepGlobal);
173             hwvtepConnectionInstance.setInstanceIdentifier(iid.firstIdentifierOf(Node.class));
174
175             // Register Cluster Ownership for ConnectionInfo
176             registerEntityForOwnership(hwvtepConnectionInstance);
177         } else {
178             LOG.warn("Failed to connect to OVSDB node: {}", hwvtepGlobal.getConnectionInfo());
179         }
180         return client;
181     }
182     public void disconnect(HwvtepGlobalAugmentation ovsdbNode) throws UnknownHostException {
183         LOG.info("Diconnecting from {}", HwvtepSouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
184         HwvtepConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
185         if (client != null) {
186             client.disconnect();
187             // Unregister Cluster Ownership for ConnectionInfo
188             unregisterEntityForOwnership(client);
189             removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
190         }
191     }
192
193     public HwvtepConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
194         LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
195                 externalClient.getConnectionInfo().getRemotePort());
196         ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(externalClient);
197         HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
198
199         // Check if existing hwvtepConnectionInstance for the OvsdbClient present.
200         // In such cases, we will see if the hwvtepConnectionInstance has same externalClient.
201         if (hwvtepConnectionInstance != null) {
202             if (hwvtepConnectionInstance.hasOvsdbClient(externalClient)) {
203                 LOG.warn("HWVTEP Connection Instance {} already exists for client {}", key, externalClient);
204                 return hwvtepConnectionInstance;
205             }
206             LOG.warn("HWVTEP Connection Instance {} being replaced with client {}", key, externalClient);
207             hwvtepConnectionInstance.disconnect();
208
209             // Unregister Cluster Ownership for ConnectionInfo
210             // Because the hwvtepConnectionInstance is about to be completely replaced!
211             unregisterEntityForOwnership(hwvtepConnectionInstance);
212
213             removeConnectionInstance(key);
214         }
215
216         hwvtepConnectionInstance = new HwvtepConnectionInstance(key, externalClient, getInstanceIdentifier(key),
217                 txInvoker, db);
218         hwvtepConnectionInstance.createTransactInvokers();
219         return hwvtepConnectionInstance;
220     }
221
222     private void putConnectionInstance(ConnectionInfo key,HwvtepConnectionInstance instance) {
223         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
224         clients.put(connectionInfo, instance);
225         LOG.info("Clients after put: {}", clients);
226     }
227
228     public HwvtepConnectionInstance getConnectionInstance(final ConnectionInfo key) {
229         if (key == null) {
230             return null;
231         }
232         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
233         return clients.get(connectionInfo);
234     }
235
236     public HwvtepConnectionInstance getConnectionInstance(Node node) {
237         Preconditions.checkNotNull(node);
238         HwvtepGlobalAugmentation hwvtepGlobal = node.getAugmentation(HwvtepGlobalAugmentation.class);
239         PhysicalSwitchAugmentation pSwitchNode = node.getAugmentation(PhysicalSwitchAugmentation.class);
240         if (hwvtepGlobal != null) {
241             if(hwvtepGlobal.getConnectionInfo() != null) {
242                 return getConnectionInstance(hwvtepGlobal.getConnectionInfo());
243             } else {
244                 //TODO: Case of user configured connection for now
245                 //TODO: We could get it from Managers also.
246                 return null;
247             }
248         }
249         else if(pSwitchNode != null){
250             return getConnectionInstance(pSwitchNode);
251         } else {
252             LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
253             return null;
254         }
255     }
256
257     public HwvtepConnectionInstance getConnectionInstance(HwvtepPhysicalSwitchAttributes pNode) {
258         Optional<HwvtepGlobalAugmentation> optional = HwvtepSouthboundUtil.getManagingNode(db, pNode);
259         if(optional.isPresent()) {
260             return getConnectionInstance(optional.get().getConnectionInfo());
261         } else {
262             return null;
263         }
264     }
265
266     public void stopConfigurationReconciliation(final InstanceIdentifier<Node> nodeIid) {
267         final ReconciliationTask task = new HwvtepReconciliationTask(
268                 reconciliationManager, HwvtepConnectionManager.this, nodeIid, null, null, db);
269
270         reconciliationManager.dequeue(task);
271     }
272
273     public void reconcileConfigurations(final HwvtepConnectionInstance client, Node psNode) {
274         final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
275         final ReconciliationTask task = new HwvtepReconciliationTask(
276                 reconciliationManager, HwvtepConnectionManager.this, nodeIid, psNode, client, db);
277
278         reconciliationManager.enqueue(task);
279     }
280
281     private void removeConnectionInstance(ConnectionInfo key) {
282         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
283         clients.remove(connectionInfo);
284         LOG.info("Clients after remove: {}", clients);
285     }
286
287     private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
288         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
289         instanceIdentifiers.put(connectionInfo, iid);
290     }
291
292     public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
293         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
294         return instanceIdentifiers.get(connectionInfo);
295     }
296
297     private void removeInstanceIdentifier(ConnectionInfo key) {
298         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
299         instanceIdentifiers.remove(connectionInfo);
300     }
301
302     public OvsdbClient getClient(ConnectionInfo connectionInfo) {
303         return getConnectionInstance(connectionInfo).getOvsdbClient();
304     }
305
306     private void registerEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
307
308         Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
309         entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
310         hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
311
312         try {
313             EntityOwnershipCandidateRegistration registration =
314                     entityOwnershipService.registerCandidate(candidateEntity);
315             hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
316             LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
317
318             //If entity already has owner, it won't get notification from EntityOwnershipService
319             //so cache the connection instances.
320             Optional<EntityOwnershipState> ownershipStateOpt =
321                     entityOwnershipService.getOwnershipState(candidateEntity);
322             if (ownershipStateOpt.isPresent()) {
323                 EntityOwnershipState ownershipState = ownershipStateOpt.get();
324                 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
325                     if (getConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo()) != null) {
326                         LOG.info("OVSDB entity {} is already owned by other southbound plugin "
327                                 + "instance, so *this* instance is NOT an OWNER of the device",
328                                 hwvtepConnectionInstance.getConnectionInfo());
329                         putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
330                     }
331                 }
332             }
333         } catch (CandidateAlreadyRegisteredException e) {
334             LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
335         }
336
337     }
338
339     private Global getHwvtepGlobalTableEntry(HwvtepConnectionInstance connectionInstance) {
340         DatabaseSchema dbSchema = null;
341         Global globalRow = null;
342
343         try {
344             dbSchema = connectionInstance.getSchema(HwvtepSchemaConstants.HARDWARE_VTEP).get();
345         } catch (InterruptedException | ExecutionException e) {
346             LOG.warn("Not able to fetch schema for database {} from device {}",
347                     HwvtepSchemaConstants.HARDWARE_VTEP,connectionInstance.getConnectionInfo(),e);
348         }
349
350         if (dbSchema != null) {
351             GenericTableSchema hwvtepSchema = TyperUtils.getTableSchema(dbSchema, Global.class);
352
353             List<String> hwvtepTableColumn = new ArrayList<>();
354             hwvtepTableColumn.addAll(hwvtepSchema.getColumns());
355             Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
356             selectOperation.setColumns(hwvtepTableColumn);
357
358             ArrayList<Operation> operations = new ArrayList<>();
359             operations.add(selectOperation);
360             operations.add(op.comment("Fetching hardware_vtep table rows"));
361
362             try {
363                 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
364                 if (results != null ) {
365                     OperationResult selectResult = results.get(0);
366                     globalRow = TyperUtils.getTypedRowWrapper(
367                             dbSchema,Global.class,selectResult.getRows().get(0));
368                 }
369             } catch (InterruptedException | ExecutionException e) {
370                 LOG.warn("Not able to fetch hardware_vtep table row from device {}",
371                         connectionInstance.getConnectionInfo(),e);
372             }
373         }
374         LOG.trace("Fetched global {} from hardware_vtep schema",globalRow);
375         return globalRow;
376     }
377
378     private Entity getEntityFromConnectionInstance(@Nonnull HwvtepConnectionInstance hwvtepConnectionInstance) {
379         InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
380         if ( iid == null ) {
381             //TODO: Is Global the right one?
382             Global hwvtepGlobalRow = getHwvtepGlobalTableEntry(hwvtepConnectionInstance);
383             iid = HwvtepSouthboundMapper.getInstanceIdentifier(hwvtepGlobalRow);
384             /* Let's set the iid now */
385             hwvtepConnectionInstance.setInstanceIdentifier(iid);
386             LOG.info("InstanceIdentifier {} generated for device "
387                     + "connection {}",iid, hwvtepConnectionInstance.getConnectionInfo());
388
389         }
390         YangInstanceIdentifier entityId =
391                 HwvtepSouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
392         Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
393         LOG.debug("Entity {} created for device connection {}",
394                 deviceEntity, hwvtepConnectionInstance.getConnectionInfo());
395         return deviceEntity;
396     }
397     private void unregisterEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
398         hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
399         entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
400     }
401
402     public void reconcileConnection(InstanceIdentifier<Node> iid, HwvtepGlobalAugmentation hwvtepNode) {
403         this.retryConnection(iid, hwvtepNode,
404                 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
405         }
406
407     public void stopConnectionReconciliationIfActive(InstanceIdentifier<?> iid, HwvtepGlobalAugmentation hwvtepNode) {
408         final ReconciliationTask task = new ConnectionReconciliationTask(
409                 reconciliationManager,
410                 this,
411                 iid,
412                 hwvtepNode);
413         reconciliationManager.dequeue(task);
414     }
415
416     private void retryConnection(final InstanceIdentifier<Node> iid, final HwvtepGlobalAugmentation hwvtepNode,
417                                  ConnectionReconciliationTriggers trigger) {
418         final ReconciliationTask task = new ConnectionReconciliationTask(
419                 reconciliationManager,
420                 this,
421                 iid,
422                 hwvtepNode);
423
424         if(reconciliationManager.isEnqueued(task)){
425             return;
426         }
427         switch(trigger){
428             case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
429                 reconciliationManager.enqueueForRetry(task);
430                 break;
431             case ON_DISCONNECT:
432             {
433                 ReadOnlyTransaction tx = db.newReadOnlyTransaction();
434                 CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture =
435                         tx.read(LogicalDatastoreType.CONFIGURATION, iid);
436
437                 final HwvtepConnectionManager connectionManager = this;
438                 Futures.addCallback(readNodeFuture, new FutureCallback<Optional<Node>>() {
439                     @Override
440                     public void onSuccess(@Nullable Optional<Node> node) {
441                         if (node.isPresent()) {
442                             LOG.info("Disconnected/Failed connection {} was controller initiated, attempting " +
443                                     "reconnection", hwvtepNode.getConnectionInfo());
444                             reconciliationManager.enqueue(task);
445
446                         } else {
447                             LOG.debug("Connection {} was switch initiated, no reconciliation is required"
448                                     , iid.firstKeyOf(Node.class).getNodeId());
449                         }
450                     }
451
452                     @Override
453                     public void onFailure(Throwable t) {
454                         LOG.warn("Read Config/DS for Node failed! {}", iid, t);
455                     }
456                 });
457                 break;
458             }
459             default:
460                 break;
461         }
462     }
463
464     public void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
465         HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
466         LOG.info("handleOwnershipChanged: {} event received for device {}",
467                 ownershipChange, hwvtepConnectionInstance != null ? hwvtepConnectionInstance.getConnectionInfo()
468                         : "THAT'S NOT REGISTERED BY THIS SOUTHBOUND PLUGIN INSTANCE");
469
470         if (hwvtepConnectionInstance == null) {
471             if (ownershipChange.isOwner()) {
472                 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
473             } else {
474                 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
475                 // that instance registered for the device ownership or not. It is to make sure that
476                 // If all the controller instance that was connected to the device are down, so the
477                 // running instance can clear up the operational data store even though it was not
478                 // connected to the device.
479                 LOG.debug("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
480             }
481
482             // If entity has no owner, clean up the operational data store (it's possible because owner controller
483             // might went down abruptly and didn't get a chance to clean up the operational data store.
484             if (!ownershipChange.hasOwner()) {
485                 LOG.debug("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
486                 // Below code might look weird but it's required. We want to give first opportunity to the
487                 // previous owner of the device to clean up the operational data store if there is no owner now.
488                 // That way we will avoid lot of nasty md-sal exceptions because of concurrent delete.
489                 if (ownershipChange.wasOwner()) {
490                     cleanEntityOperationalData(ownershipChange.getEntity());
491                 }
492                 // If first cleanEntityOperationalData() was called, this call will be no-op.
493                 cleanEntityOperationalData(ownershipChange.getEntity());
494             }
495             return;
496         }
497         //Connection detail need to be cached, irrespective of ownership result.
498         putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(), hwvtepConnectionInstance);
499
500         if (ownershipChange.isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
501             LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
502                     hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
503             return;
504         }
505
506         hwvtepConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
507         // You were not an owner, but now you are
508         if (ownershipChange.isOwner()) {
509             LOG.info("handleOwnershipChanged: *this* southbound plugin instance is owner of device {}",
510                     hwvtepConnectionInstance.getConnectionInfo());
511
512             //*this* instance of southbound plugin is owner of the device,
513             //so register for monitor callbacks
514             hwvtepConnectionInstance.registerCallbacks();
515
516         } else {
517             //You were owner of the device, but now you are not. With the current ownership
518             //grant mechanism, this scenario should not occur. Because this scenario will occur
519             //when this controller went down or switch flap the connection, but in both the case
520             //it will go through the re-registration process. We need to implement this condition
521             //when clustering service implement a ownership grant strategy which can revoke the
522             //device ownership for load balancing the devices across the instances.
523             //Once this condition occur, we should unregister the callback.
524             LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}",
525                     hwvtepConnectionInstance.getNodeId().getValue());
526         }
527     }
528
529     private void cleanEntityOperationalData(Entity entity) {
530         @SuppressWarnings("unchecked") final InstanceIdentifier<Node> nodeIid =
531                 (InstanceIdentifier<Node>) HwvtepSouthboundUtil
532                         .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
533
534         txInvoker.invoke(new TransactionCommand() {
535             @Override
536             public void execute(ReadWriteTransaction transaction) {
537                 transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
538             }
539         });
540     }
541
542     private HwvtepConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
543         return entityConnectionMap.get(entity);
544     }
545
546     private class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
547         private HwvtepConnectionManager hcm;
548         private EntityOwnershipListenerRegistration listenerRegistration;
549
550         HwvtepDeviceEntityOwnershipListener(HwvtepConnectionManager hcm, EntityOwnershipService entityOwnershipService) {
551             this.hcm = hcm;
552             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
553         }
554         public void close() {
555             listenerRegistration.close();
556         }
557         @Override
558         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
559             hcm.handleOwnershipChanged(ownershipChange);
560         }
561     }
562
563     private enum ConnectionReconciliationTriggers {
564         /*
565         Reconciliation trigger for scenario where controller's attempt
566         to connect to switch fails on config data store notification
567         */
568         ON_CONTROLLER_INITIATED_CONNECTION_FAILURE,
569
570         /*
571         Reconciliation trigger for the scenario where controller
572         initiated connection disconnects.
573         */
574         ON_DISCONNECT
575     }
576 }