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