bug 6579 added dependency queue
[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(ConnectionInfo key) {
229         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
230         return clients.get(connectionInfo);
231     }
232
233     public HwvtepConnectionInstance getConnectionInstance(Node node) {
234         Preconditions.checkNotNull(node);
235         HwvtepGlobalAugmentation hwvtepGlobal = node.getAugmentation(HwvtepGlobalAugmentation.class);
236         PhysicalSwitchAugmentation pSwitchNode = node.getAugmentation(PhysicalSwitchAugmentation.class);
237         if (hwvtepGlobal != null) {
238             if(hwvtepGlobal.getConnectionInfo() != null) {
239                 return getConnectionInstance(hwvtepGlobal.getConnectionInfo());
240             } else {
241                 //TODO: Case of user configured connection for now
242                 //TODO: We could get it from Managers also.
243                 return null;
244             }
245         }
246         else if(pSwitchNode != null){
247             return getConnectionInstance(pSwitchNode);
248         } else {
249             LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
250             return null;
251         }
252     }
253
254     public HwvtepConnectionInstance getConnectionInstance(HwvtepPhysicalSwitchAttributes pNode) {
255         Optional<HwvtepGlobalAugmentation> optional = HwvtepSouthboundUtil.getManagingNode(db, pNode);
256         if(optional.isPresent()) {
257             return getConnectionInstance(optional.get().getConnectionInfo());
258         } else {
259             return null;
260         }
261     }
262
263     public void stopConfigurationReconciliation(final InstanceIdentifier<Node> nodeIid) {
264         final ReconciliationTask task = new HwvtepReconciliationTask(
265                 reconciliationManager, HwvtepConnectionManager.this, nodeIid, null, null, db);
266
267         reconciliationManager.dequeue(task);
268     }
269
270     public void reconcileConfigurations(final HwvtepConnectionInstance client, Node psNode) {
271         final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
272         final ReconciliationTask task = new HwvtepReconciliationTask(
273                 reconciliationManager, HwvtepConnectionManager.this, nodeIid, psNode, client, db);
274
275         reconciliationManager.enqueue(task);
276     }
277
278     private void removeConnectionInstance(ConnectionInfo key) {
279         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
280         clients.remove(connectionInfo);
281         LOG.info("Clients after remove: {}", clients);
282     }
283
284     private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
285         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
286         instanceIdentifiers.put(connectionInfo, iid);
287     }
288
289     public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
290         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
291         return instanceIdentifiers.get(connectionInfo);
292     }
293
294     private void removeInstanceIdentifier(ConnectionInfo key) {
295         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
296         instanceIdentifiers.remove(connectionInfo);
297     }
298
299     public OvsdbClient getClient(ConnectionInfo connectionInfo) {
300         return getConnectionInstance(connectionInfo).getOvsdbClient();
301     }
302
303     private void registerEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
304
305         Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
306         entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
307         hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
308
309         try {
310             EntityOwnershipCandidateRegistration registration =
311                     entityOwnershipService.registerCandidate(candidateEntity);
312             hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
313             LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
314
315             //If entity already has owner, it won't get notification from EntityOwnershipService
316             //so cache the connection instances.
317             Optional<EntityOwnershipState> ownershipStateOpt =
318                     entityOwnershipService.getOwnershipState(candidateEntity);
319             if (ownershipStateOpt.isPresent()) {
320                 EntityOwnershipState ownershipState = ownershipStateOpt.get();
321                 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
322                     if (getConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo()) != null) {
323                         LOG.info("OVSDB entity {} is already owned by other southbound plugin "
324                                 + "instance, so *this* instance is NOT an OWNER of the device",
325                                 hwvtepConnectionInstance.getConnectionInfo());
326                         putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
327                     }
328                 }
329             }
330         } catch (CandidateAlreadyRegisteredException e) {
331             LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
332         }
333
334     }
335
336     private Global getHwvtepGlobalTableEntry(HwvtepConnectionInstance connectionInstance) {
337         DatabaseSchema dbSchema = null;
338         Global globalRow = null;
339
340         try {
341             dbSchema = connectionInstance.getSchema(HwvtepSchemaConstants.HARDWARE_VTEP).get();
342         } catch (InterruptedException | ExecutionException e) {
343             LOG.warn("Not able to fetch schema for database {} from device {}",
344                     HwvtepSchemaConstants.HARDWARE_VTEP,connectionInstance.getConnectionInfo(),e);
345         }
346
347         if (dbSchema != null) {
348             GenericTableSchema hwvtepSchema = TyperUtils.getTableSchema(dbSchema, Global.class);
349
350             List<String> hwvtepTableColumn = new ArrayList<>();
351             hwvtepTableColumn.addAll(hwvtepSchema.getColumns());
352             Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
353             selectOperation.setColumns(hwvtepTableColumn);
354
355             ArrayList<Operation> operations = new ArrayList<>();
356             operations.add(selectOperation);
357             operations.add(op.comment("Fetching hardware_vtep table rows"));
358
359             try {
360                 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
361                 if (results != null ) {
362                     OperationResult selectResult = results.get(0);
363                     globalRow = TyperUtils.getTypedRowWrapper(
364                             dbSchema,Global.class,selectResult.getRows().get(0));
365                 }
366             } catch (InterruptedException | ExecutionException e) {
367                 LOG.warn("Not able to fetch hardware_vtep table row from device {}",
368                         connectionInstance.getConnectionInfo(),e);
369             }
370         }
371         LOG.trace("Fetched global {} from hardware_vtep schema",globalRow);
372         return globalRow;
373     }
374
375     private Entity getEntityFromConnectionInstance(@Nonnull HwvtepConnectionInstance hwvtepConnectionInstance) {
376         InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
377         if ( iid == null ) {
378             //TODO: Is Global the right one?
379             Global hwvtepGlobalRow = getHwvtepGlobalTableEntry(hwvtepConnectionInstance);
380             iid = HwvtepSouthboundMapper.getInstanceIdentifier(hwvtepGlobalRow);
381             /* Let's set the iid now */
382             hwvtepConnectionInstance.setInstanceIdentifier(iid);
383             LOG.info("InstanceIdentifier {} generated for device "
384                     + "connection {}",iid, hwvtepConnectionInstance.getConnectionInfo());
385
386         }
387         YangInstanceIdentifier entityId =
388                 HwvtepSouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
389         Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
390         LOG.debug("Entity {} created for device connection {}",
391                 deviceEntity, hwvtepConnectionInstance.getConnectionInfo());
392         return deviceEntity;
393     }
394     private void unregisterEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
395         hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
396         entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
397     }
398
399     public void reconcileConnection(InstanceIdentifier<Node> iid, HwvtepGlobalAugmentation hwvtepNode) {
400         this.retryConnection(iid, hwvtepNode,
401                 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
402         }
403
404     public void stopConnectionReconciliationIfActive(InstanceIdentifier<?> iid, HwvtepGlobalAugmentation hwvtepNode) {
405         final ReconciliationTask task = new ConnectionReconciliationTask(
406                 reconciliationManager,
407                 this,
408                 iid,
409                 hwvtepNode);
410         reconciliationManager.dequeue(task);
411     }
412
413     private void retryConnection(final InstanceIdentifier<Node> iid, final HwvtepGlobalAugmentation hwvtepNode,
414                                  ConnectionReconciliationTriggers trigger) {
415         final ReconciliationTask task = new ConnectionReconciliationTask(
416                 reconciliationManager,
417                 this,
418                 iid,
419                 hwvtepNode);
420
421         if(reconciliationManager.isEnqueued(task)){
422             return;
423         }
424         switch(trigger){
425             case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
426                 reconciliationManager.enqueueForRetry(task);
427                 break;
428             case ON_DISCONNECT:
429             {
430                 ReadOnlyTransaction tx = db.newReadOnlyTransaction();
431                 CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture =
432                         tx.read(LogicalDatastoreType.CONFIGURATION, iid);
433
434                 final HwvtepConnectionManager connectionManager = this;
435                 Futures.addCallback(readNodeFuture, new FutureCallback<Optional<Node>>() {
436                     @Override
437                     public void onSuccess(@Nullable Optional<Node> node) {
438                         if (node.isPresent()) {
439                             LOG.info("Disconnected/Failed connection {} was controller initiated, attempting " +
440                                     "reconnection", hwvtepNode.getConnectionInfo());
441                             reconciliationManager.enqueue(task);
442
443                         } else {
444                             LOG.debug("Connection {} was switch initiated, no reconciliation is required"
445                                     , iid.firstKeyOf(Node.class).getNodeId());
446                         }
447                     }
448
449                     @Override
450                     public void onFailure(Throwable t) {
451                         LOG.warn("Read Config/DS for Node failed! {}", iid, t);
452                     }
453                 });
454                 break;
455             }
456             default:
457                 break;
458         }
459     }
460
461     public void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
462         HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
463         LOG.info("handleOwnershipChanged: {} event received for device {}",
464                 ownershipChange, hwvtepConnectionInstance != null ? hwvtepConnectionInstance.getConnectionInfo()
465                         : "THAT'S NOT REGISTERED BY THIS SOUTHBOUND PLUGIN INSTANCE");
466
467         if (hwvtepConnectionInstance == null) {
468             if (ownershipChange.isOwner()) {
469                 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
470             } else {
471                 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
472                 // that instance registered for the device ownership or not. It is to make sure that
473                 // If all the controller instance that was connected to the device are down, so the
474                 // running instance can clear up the operational data store even though it was not
475                 // connected to the device.
476                 LOG.debug("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
477             }
478
479             // If entity has no owner, clean up the operational data store (it's possible because owner controller
480             // might went down abruptly and didn't get a chance to clean up the operational data store.
481             if (!ownershipChange.hasOwner()) {
482                 LOG.debug("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
483                 // Below code might look weird but it's required. We want to give first opportunity to the
484                 // previous owner of the device to clean up the operational data store if there is no owner now.
485                 // That way we will avoid lot of nasty md-sal exceptions because of concurrent delete.
486                 if (ownershipChange.wasOwner()) {
487                     cleanEntityOperationalData(ownershipChange.getEntity());
488                 }
489                 // If first cleanEntityOperationalData() was called, this call will be no-op.
490                 cleanEntityOperationalData(ownershipChange.getEntity());
491             }
492             return;
493         }
494         //Connection detail need to be cached, irrespective of ownership result.
495         putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(), hwvtepConnectionInstance);
496
497         if (ownershipChange.isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
498             LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
499                     hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
500             return;
501         }
502
503         hwvtepConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
504         // You were not an owner, but now you are
505         if (ownershipChange.isOwner()) {
506             LOG.info("handleOwnershipChanged: *this* southbound plugin instance is owner of device {}",
507                     hwvtepConnectionInstance.getConnectionInfo());
508
509             //*this* instance of southbound plugin is owner of the device,
510             //so register for monitor callbacks
511             hwvtepConnectionInstance.registerCallbacks();
512
513         } else {
514             //You were owner of the device, but now you are not. With the current ownership
515             //grant mechanism, this scenario should not occur. Because this scenario will occur
516             //when this controller went down or switch flap the connection, but in both the case
517             //it will go through the re-registration process. We need to implement this condition
518             //when clustering service implement a ownership grant strategy which can revoke the
519             //device ownership for load balancing the devices across the instances.
520             //Once this condition occur, we should unregister the callback.
521             LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}",
522                     hwvtepConnectionInstance.getNodeId().getValue());
523         }
524     }
525
526     private void cleanEntityOperationalData(Entity entity) {
527         @SuppressWarnings("unchecked") final InstanceIdentifier<Node> nodeIid =
528                 (InstanceIdentifier<Node>) HwvtepSouthboundUtil
529                         .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
530
531         txInvoker.invoke(new TransactionCommand() {
532             @Override
533             public void execute(ReadWriteTransaction transaction) {
534                 transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
535             }
536         });
537     }
538
539     private HwvtepConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
540         return entityConnectionMap.get(entity);
541     }
542
543     private class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
544         private HwvtepConnectionManager hcm;
545         private EntityOwnershipListenerRegistration listenerRegistration;
546
547         HwvtepDeviceEntityOwnershipListener(HwvtepConnectionManager hcm, EntityOwnershipService entityOwnershipService) {
548             this.hcm = hcm;
549             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
550         }
551         public void close() {
552             listenerRegistration.close();
553         }
554         @Override
555         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
556             hcm.handleOwnershipChanged(ownershipChange);
557         }
558     }
559
560     private enum ConnectionReconciliationTriggers {
561         /*
562         Reconciliation trigger for scenario where controller's attempt
563         to connect to switch fails on config data store notification
564         */
565         ON_CONTROLLER_INITIATED_CONNECTION_FAILURE,
566
567         /*
568         Reconciliation trigger for the scenario where controller
569         initiated connection disconnects.
570         */
571         ON_DISCONNECT
572     }
573 }