make sure ovsdb connected node appears in operds
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / OvsdbConnectionManager.java
1 /*
2  * Copyright © 2014, 2017 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.ovsdb.southbound;
9
10 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
20 import java.net.ConnectException;
21 import java.net.InetAddress;
22 import java.net.UnknownHostException;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
32 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
33 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
34 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
35 import org.opendaylight.mdsal.eos.binding.api.Entity;
36 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
37 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
38 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
39 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
40 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
41 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
42 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
43 import org.opendaylight.ovsdb.lib.OvsdbClient;
44 import org.opendaylight.ovsdb.lib.OvsdbConnection;
45 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
46 import org.opendaylight.ovsdb.lib.operations.Operation;
47 import org.opendaylight.ovsdb.lib.operations.OperationResult;
48 import org.opendaylight.ovsdb.lib.operations.Select;
49 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
50 import org.opendaylight.ovsdb.lib.schema.typed.TypedDatabaseSchema;
51 import org.opendaylight.ovsdb.schema.openvswitch.OpenVSwitch;
52 import org.opendaylight.ovsdb.southbound.reconciliation.ReconciliationManager;
53 import org.opendaylight.ovsdb.southbound.reconciliation.ReconciliationTask;
54 import org.opendaylight.ovsdb.southbound.reconciliation.configuration.BridgeConfigReconciliationTask;
55 import org.opendaylight.ovsdb.southbound.reconciliation.connection.ConnectionReconciliationTask;
56 import org.opendaylight.ovsdb.southbound.transactions.md.OvsdbNodeRemoveCommand;
57 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
58 import org.opendaylight.serviceutils.upgrade.UpgradeState;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
64 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
65 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoCloseable {
70
71     private final Map<ConnectionInfo, OvsdbConnectionInstance> clients =
72             new ConcurrentHashMap<>();
73     private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionManager.class);
74     private static final String ENTITY_TYPE = "ovsdb";
75     private static final int DB_FETCH_TIMEOUT = 1000;
76
77     private final DataBroker db;
78     private final TransactionInvoker txInvoker;
79     private final Map<OvsdbClient, OvsdbClient> alreadyProcessedClients = new ConcurrentHashMap<>();
80     private final Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
81             new ConcurrentHashMap<>();
82     private final Map<InstanceIdentifier<Node>, OvsdbConnectionInstance> nodeIdVsConnectionInstance =
83             new ConcurrentHashMap<>();
84     private final Map<Entity, OvsdbConnectionInstance> entityConnectionMap =
85             new ConcurrentHashMap<>();
86     private final EntityOwnershipService entityOwnershipService;
87     private final OvsdbDeviceEntityOwnershipListener ovsdbDeviceEntityOwnershipListener;
88     private final OvsdbConnection ovsdbConnection;
89     private final ReconciliationManager reconciliationManager;
90     private final InstanceIdentifierCodec instanceIdentifierCodec;
91     private final UpgradeState upgradeState;
92
93     public OvsdbConnectionManager(final DataBroker db,final TransactionInvoker txInvoker,
94                                   final EntityOwnershipService entityOwnershipService,
95                                   final OvsdbConnection ovsdbConnection,
96                                   final InstanceIdentifierCodec instanceIdentifierCodec,
97                                   final UpgradeState upgradeState) {
98         this.db = db;
99         this.txInvoker = txInvoker;
100         this.entityOwnershipService = entityOwnershipService;
101         this.ovsdbDeviceEntityOwnershipListener = new OvsdbDeviceEntityOwnershipListener(this, entityOwnershipService);
102         this.ovsdbConnection = ovsdbConnection;
103         this.reconciliationManager = new ReconciliationManager(db, instanceIdentifierCodec);
104         this.instanceIdentifierCodec = instanceIdentifierCodec;
105         this.upgradeState = upgradeState;
106     }
107
108     @Override
109     public void connected(final OvsdbClient externalClient) {
110         if (alreadyProcessedClients.containsKey(externalClient)) {
111             LOG.info("OvsdbConnectionManager Library already connected {} from {}:{} to {}:{} "
112                             + "to this, hence skipping the processing",
113                     externalClient.getConnectionInfo().getType(),
114                     externalClient.getConnectionInfo().getRemoteAddress(),
115                     externalClient.getConnectionInfo().getRemotePort(),
116                     externalClient.getConnectionInfo().getLocalAddress(),
117                     externalClient.getConnectionInfo().getLocalPort());
118             return;
119         }
120         alreadyProcessedClients.put(externalClient, externalClient);
121
122         LOG.info("OvsdbConnectionManager connected {} from {}:{} to {}:{}",
123                 externalClient.getConnectionInfo().getType(),
124                 externalClient.getConnectionInfo().getRemoteAddress(),
125                 externalClient.getConnectionInfo().getRemotePort(),
126                 externalClient.getConnectionInfo().getLocalAddress(),
127                 externalClient.getConnectionInfo().getLocalPort());
128         try {
129             List<String> databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
130             if (databases.contains(SouthboundConstants.OPEN_V_SWITCH)) {
131                 OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
132                 // Register Cluster Ownership for ConnectionInfo
133                 registerEntityForOwnership(client);
134                 OvsdbOperGlobalListener.runAfterTimeoutIfNodeNotCreated(client.getInstanceIdentifier(), () -> {
135                     externalClient.disconnect();
136                     disconnected(externalClient);
137                 });
138             }
139         } catch (InterruptedException | ExecutionException | TimeoutException e) {
140             LOG.warn("OvsdbConnectionManager Unable to fetch Database list from device {}."
141                     + "Disconnecting from the device.", externalClient.getConnectionInfo().getRemoteAddress(), e);
142             externalClient.disconnect();
143         }
144
145     }
146
147     public OvsdbConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
148         LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
149                 externalClient.getConnectionInfo().getRemotePort());
150         ConnectionInfo key = SouthboundMapper.createConnectionInfo(externalClient);
151         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
152
153         // Check if existing ovsdbConnectionInstance for the OvsdbClient present.
154         // In such cases, we will see if the ovsdbConnectionInstance has same externalClient.
155         if (ovsdbConnectionInstance != null) {
156             if (ovsdbConnectionInstance.hasOvsdbClient(externalClient)) {
157                 LOG.warn("OVSDB Connection Instance {} already exists for client {}", key, externalClient);
158                 return ovsdbConnectionInstance;
159             }
160             LOG.warn("OVSDB Connection Instance {} being replaced with client {}", key, externalClient);
161
162             // Unregister Cluster Ownership for ConnectionInfo
163             // Because the ovsdbConnectionInstance is about to be completely replaced!
164             unregisterEntityForOwnership(ovsdbConnectionInstance);
165
166             ovsdbConnectionInstance.disconnect();
167
168             removeConnectionInstance(key);
169
170             stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
171         }
172
173         ovsdbConnectionInstance = new OvsdbConnectionInstance(key, externalClient, txInvoker,
174                 getInstanceIdentifier(key));
175         ovsdbConnectionInstance.createTransactInvokers();
176         return ovsdbConnectionInstance;
177     }
178
179     @Override
180     public void disconnected(final OvsdbClient client) {
181         alreadyProcessedClients.remove(client);
182         LOG.info("Ovsdb Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
183                 client.getConnectionInfo().getType(),
184                 client.getConnectionInfo().getRemoteAddress(),
185                 client.getConnectionInfo().getRemotePort(),
186                 client.getConnectionInfo().getLocalAddress(),
187                 client.getConnectionInfo().getLocalPort());
188         ConnectionInfo key = SouthboundMapper.createConnectionInfo(client);
189         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
190         if (ovsdbConnectionInstance != null) {
191             // Unregister Entity ownership as soon as possible ,so this instance should
192             // not be used as a candidate in Entity election (given that this instance is
193             // about to disconnect as well), if current owner get disconnected from
194             // OVSDB device.
195             if (ovsdbConnectionInstance.getHasDeviceOwnership()) {
196                 LOG.info("Ovsdb Library disconnected {} this controller instance has ownership", key);
197                 deleteOperNodeAndReleaseOwnership(ovsdbConnectionInstance);
198             } else {
199                 LOG.info("Ovsdb Library disconnected {} this controller does not have ownership", key);
200                 unregisterEntityForOwnership(ovsdbConnectionInstance);
201             }
202             removeConnectionInstance(key);
203
204             //Controller initiated connection can be terminated from switch side.
205             //So cleanup the instance identifier cache.
206             removeInstanceIdentifier(key);
207             nodeIdVsConnectionInstance.remove(ovsdbConnectionInstance.getInstanceIdentifier(),
208                     ovsdbConnectionInstance);
209             stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
210             retryConnection(ovsdbConnectionInstance.getInstanceIdentifier(),
211                     ovsdbConnectionInstance.getOvsdbNodeAugmentation(),
212                     ConnectionReconciliationTriggers.ON_DISCONNECT);
213         } else {
214             LOG.warn("Ovsdb disconnected : Connection instance not found for OVSDB Node {} ", key);
215         }
216         LOG.trace("OvsdbConnectionManager: exit disconnected client: {}", client);
217     }
218
219     private void deleteOperNodeAndReleaseOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
220         ovsdbConnectionInstance.setHasDeviceOwnership(false);
221         final InstanceIdentifier nodeIid = ovsdbConnectionInstance.getInstanceIdentifier();
222         //remove the node from oper only if it has ownership
223         txInvoker.invoke(new OvsdbNodeRemoveCommand(ovsdbConnectionInstance, null, null) {
224
225             @Override
226             public void onSuccess() {
227                 super.onSuccess();
228                 LOG.debug("Successfully removed node {} from oper", nodeIid);
229                 //Giveup the ownership only after cleanup is done
230                 unregisterEntityForOwnership(ovsdbConnectionInstance);
231             }
232
233             @Override
234             public void onFailure(final Throwable throwable) {
235                 LOG.debug("Failed to remove node {} from oper", nodeIid);
236                 super.onFailure(throwable);
237                 unregisterEntityForOwnership(ovsdbConnectionInstance);
238             }
239         });
240     }
241
242     public OvsdbClient connect(final InstanceIdentifier<Node> iid,
243             final OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException, ConnectException {
244         LOG.info("Connecting to {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
245
246         // TODO handle case where we already have a connection
247         // TODO use transaction chains to handle ordering issues between disconnected
248         // TODO and connected when writing to the operational store
249         InetAddress ip = SouthboundMapper.createInetAddress(ovsdbNode.getConnectionInfo().getRemoteIp());
250         OvsdbClient client = ovsdbConnection.connect(ip,
251                 ovsdbNode.getConnectionInfo().getRemotePort().getValue().toJava());
252         // For connections from the controller to the ovs instance, the library doesn't call
253         // this method for us
254         if (client != null) {
255             putInstanceIdentifier(ovsdbNode.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
256             OvsdbConnectionInstance ovsdbConnectionInstance = connectedButCallBacksNotRegistered(client);
257             ovsdbConnectionInstance.setOvsdbNodeAugmentation(ovsdbNode);
258
259             // Register Cluster Ownership for ConnectionInfo
260             registerEntityForOwnership(ovsdbConnectionInstance);
261         } else {
262             LOG.warn("Failed to connect to OVSDB Node {}", ovsdbNode.getConnectionInfo());
263         }
264         return client;
265     }
266
267     public void disconnect(final OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
268         LOG.info("Disconnecting from {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
269         OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
270         if (client != null) {
271             // Unregister Cluster Onwership for ConnectionInfo
272             deleteOperNodeAndReleaseOwnership(client);
273
274             client.disconnect();
275
276             removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
277
278             stopBridgeConfigReconciliationIfActive(client.getInstanceIdentifier());
279         } else {
280             LOG.debug("disconnect : connection instance not found for {}",ovsdbNode.getConnectionInfo());
281         }
282     }
283
284 /*    public void init(ConnectionInfo key) {
285         OvsdbConnectionInstance client = getConnectionInstance(key);
286
287         // TODO (FF): make sure that this cluster instance is the 'entity owner' fo the given OvsdbConnectionInstance ?
288
289         if (client != null) {
290
291              *  Note: registerCallbacks() is idemPotent... so if you call it repeatedly all is safe,
292              *  it only registersCallbacks on the *first* call.
293
294             client.registerCallbacks();
295         }
296     }
297 */
298     @Override
299     public void close() {
300         if (ovsdbDeviceEntityOwnershipListener != null) {
301             ovsdbDeviceEntityOwnershipListener.close();
302         }
303
304         for (OvsdbConnectionInstance client: clients.values()) {
305             client.disconnect();
306         }
307     }
308
309     @VisibleForTesting
310     void putConnectionInstance(final ConnectionInfo key,final OvsdbConnectionInstance instance) {
311         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
312         clients.put(connectionInfo, instance);
313     }
314
315     private void removeConnectionInstance(final ConnectionInfo key) {
316         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
317         clients.remove(connectionInfo);
318     }
319
320     @VisibleForTesting
321     void putInstanceIdentifier(final ConnectionInfo key, final InstanceIdentifier<Node> iid) {
322         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
323         instanceIdentifiers.put(connectionInfo, iid);
324     }
325
326     private void removeInstanceIdentifier(final ConnectionInfo key) {
327         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
328         instanceIdentifiers.remove(connectionInfo);
329     }
330
331     public InstanceIdentifier<Node> getInstanceIdentifier(final ConnectionInfo key) {
332         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
333         return instanceIdentifiers.get(connectionInfo);
334     }
335
336     public OvsdbConnectionInstance getConnectionInstance(final ConnectionInfo key) {
337         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
338         return clients.get(connectionInfo);
339     }
340
341     public OvsdbConnectionInstance getConnectionInstance(final OvsdbBridgeAttributes mn) {
342         Optional<OvsdbNodeAugmentation> optional = SouthboundUtil.getManagingNode(db, mn);
343         if (optional.isPresent()) {
344             return getConnectionInstance(optional.get().getConnectionInfo());
345         } else {
346             return null;
347         }
348     }
349
350     public OvsdbConnectionInstance getConnectionInstance(final Node node) {
351         Preconditions.checkNotNull(node);
352         OvsdbNodeAugmentation ovsdbNode = node.augmentation(OvsdbNodeAugmentation.class);
353         OvsdbBridgeAugmentation ovsdbManagedNode = node.augmentation(OvsdbBridgeAugmentation.class);
354         if (ovsdbNode != null) {
355             return getConnectionInstance(ovsdbNode.getConnectionInfo());
356         } else if (ovsdbManagedNode != null) {
357             return getConnectionInstance(ovsdbManagedNode);
358         } else {
359             LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
360             return null;
361         }
362     }
363
364     public OvsdbConnectionInstance getConnectionInstance(final InstanceIdentifier<Node> nodePath) {
365         if (nodeIdVsConnectionInstance.get(nodePath) != null) {
366             return nodeIdVsConnectionInstance.get(nodePath);
367         }
368         try {
369             ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
370             CheckedFuture<Optional<Node>, ReadFailedException> nodeFuture = transaction.read(
371                     LogicalDatastoreType.OPERATIONAL, nodePath);
372             transaction.close();
373             Optional<Node> optional = nodeFuture.get();
374             if (optional.isPresent()) {
375                 return this.getConnectionInstance(optional.get());
376             } else {
377                 LOG.debug("Node was not found on the path in the operational DS: {}", nodePath);
378                 return null;
379             }
380         } catch (InterruptedException | ExecutionException e) {
381             LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
382             return null;
383         }
384     }
385
386     public OvsdbClient getClient(final ConnectionInfo connectionInfo) {
387         OvsdbConnectionInstance connectionInstance = getConnectionInstance(connectionInfo);
388         if (connectionInstance != null) {
389             return connectionInstance.getOvsdbClient();
390         }
391         return null;
392     }
393
394     public OvsdbClient getClient(final OvsdbBridgeAttributes mn) {
395         return getConnectionInstance(mn).getOvsdbClient();
396     }
397
398     public OvsdbClient getClient(final Node node) {
399         return getConnectionInstance(node).getOvsdbClient();
400     }
401
402     public Boolean getHasDeviceOwnership(final ConnectionInfo connectionInfo) {
403         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(connectionInfo);
404         if (ovsdbConnectionInstance == null) {
405             return Boolean.FALSE;
406         }
407         return ovsdbConnectionInstance.getHasDeviceOwnership();
408     }
409
410     public void reconcileConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode) {
411         this.retryConnection(iid, ovsdbNode,
412                 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
413
414     }
415
416     public void stopConnectionReconciliationIfActive(final InstanceIdentifier<Node> iid,
417             final OvsdbNodeAugmentation ovsdbNode) {
418         final ReconciliationTask task = new ConnectionReconciliationTask(
419                 reconciliationManager,
420                 this,
421                 iid,
422                 ovsdbNode);
423         reconciliationManager.dequeue(task);
424     }
425
426     public void stopBridgeConfigReconciliationIfActive(final InstanceIdentifier<Node> iid) {
427         final ReconciliationTask task =
428                 new BridgeConfigReconciliationTask(reconciliationManager, this, iid, null, instanceIdentifierCodec);
429         reconciliationManager.dequeue(task);
430         reconciliationManager.cancelTerminationPointReconciliation();
431     }
432
433     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
434             justification = "https://github.com/spotbugs/spotbugs/issues/811")
435     private void handleOwnershipChanged(final EntityOwnershipChange ownershipChange) {
436         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
437         LOG.debug("Ovsdb handleOwnershipChanged: {} event received for device {}",
438                 ownershipChange, ovsdbConnectionInstance != null ? ovsdbConnectionInstance.getConnectionInfo()
439                         : "that's currently NOT registered by *this* southbound plugin instance");
440
441         if (ovsdbConnectionInstance == null) {
442             if (ownershipChange.getState().isOwner()) {
443                 LOG.warn("Ovsdb handleOwnershipChanged: *this* instance is elected as an owner of the device {} but it "
444                         + "is NOT registered for ownership", ownershipChange.getEntity());
445             } else {
446                 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
447                 // that instance registered for the device ownership or not. It is to make sure that
448                 // If all the controller instance that was connected to the device are down, so the
449                 // running instance can clear up the operational data store even though it was not
450                 // connected to the device.
451                 LOG.debug("Ovsdb handleOwnershipChanged: No connection instance found for {}",
452                     ownershipChange.getEntity());
453             }
454
455             // If entity has no owner, clean up the operational data store (it's possible because owner controller
456             // might went down abruptly and didn't get a chance to clean up the operational data store.
457             if (!ownershipChange.getState().hasOwner()) {
458                 LOG.info("Ovsdb {} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
459                 cleanEntityOperationalData(ownershipChange.getEntity());
460             }
461             return;
462         }
463         //Connection detail need to be cached, irrespective of ownership result.
464         putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
465
466         if (ownershipChange.getState().isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
467             LOG.info("Ovsdb handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
468                     ovsdbConnectionInstance.getConnectionInfo(), ovsdbConnectionInstance.getHasDeviceOwnership()
469                             ? SouthboundConstants.OwnershipStates.OWNER.getState()
470                             : SouthboundConstants.OwnershipStates.NONOWNER.getState());
471             return;
472         }
473
474         ovsdbConnectionInstance.setHasDeviceOwnership(ownershipChange.getState().isOwner());
475         // You were not an owner, but now you are
476         if (ownershipChange.getState().isOwner()) {
477             LOG.info("Ovsdb handleOwnershipChanged: *this* southbound plugin instance is an OWNER of the device {}",
478                     ovsdbConnectionInstance.getConnectionInfo());
479
480             //*this* instance of southbound plugin is owner of the device,
481             //so register for monitor callbacks
482             ovsdbConnectionInstance.registerCallbacks(instanceIdentifierCodec);
483             LOG.trace("Ovsdb isUpgradeInProgress {}", upgradeState.isUpgradeInProgress());
484             if (!upgradeState.isUpgradeInProgress()) {
485                 reconcileBridgeConfigurations(ovsdbConnectionInstance);
486             }
487         } else {
488             //You were owner of the device, but now you are not. With the current ownership
489             //grant mechanism, this scenario should not occur. Because this scenario will occur
490             //when this controller went down or switch flap the connection, but in both the case
491             //it will go through the re-registration process. We need to implement this condition
492             //when clustering service implement a ownership grant strategy which can revoke the
493             //device ownership for load balancing the devices across the instances.
494             //Once this condition occur, we should unregister the callback.
495             LOG.error("Ovsdb handleOwnershipChanged: *this* southbound plugin instance is no longer"
496                     + " the owner of device {}.This should NOT happen.",
497                     ovsdbConnectionInstance.getNodeId().getValue());
498         }
499     }
500
501     private void cleanEntityOperationalData(final Entity entity) {
502
503         //Do explicit cleanup rather than using OvsdbNodeRemoveCommand, because there
504         // are chances that other controller instance went down abruptly and it does
505         // not clear manager entry, which OvsdbNodeRemoveCommand look for before cleanup.
506
507         @SuppressWarnings("unchecked")
508         final InstanceIdentifier<Node> nodeIid = (InstanceIdentifier<Node>) entity.getIdentifier();
509
510         txInvoker.invoke(transaction -> {
511             Optional<Node> ovsdbNodeOpt = SouthboundUtil.readNode(transaction, nodeIid);
512             if (ovsdbNodeOpt.isPresent()) {
513                 Node ovsdbNode = ovsdbNodeOpt.get();
514                 OvsdbNodeAugmentation nodeAugmentation = ovsdbNode.augmentation(OvsdbNodeAugmentation.class);
515                 if (nodeAugmentation != null) {
516                     if (nodeAugmentation.getManagedNodeEntry() != null) {
517                         for (ManagedNodeEntry managedNode : nodeAugmentation.getManagedNodeEntry()) {
518                             transaction.delete(
519                                     LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
520                         }
521                     } else {
522                         LOG.debug("{} had no managed nodes", ovsdbNode.getNodeId().getValue());
523                     }
524                 }
525                 transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
526             }
527         });
528
529     }
530
531     private static OpenVSwitch getOpenVswitchTableEntry(final OvsdbConnectionInstance connectionInstance) {
532         final TypedDatabaseSchema dbSchema;
533         try {
534             dbSchema = connectionInstance.getSchema(OvsdbSchemaContants.DATABASE_NAME).get();
535         } catch (InterruptedException | ExecutionException e) {
536             LOG.warn("Ovsdb Not able to fetch schema for database {} from device {}",
537                     OvsdbSchemaContants.DATABASE_NAME,connectionInstance.getConnectionInfo(),e);
538             return null;
539         }
540
541         final GenericTableSchema openVSwitchSchema = dbSchema.getTableSchema(OpenVSwitch.class);
542         final Select<GenericTableSchema> selectOperation = op.select(openVSwitchSchema);
543         selectOperation.setColumns(openVSwitchSchema.getColumnList());
544
545         List<Operation> operations = new ArrayList<>();
546         operations.add(selectOperation);
547         operations.add(op.comment("Fetching Open_VSwitch table rows"));
548         final List<OperationResult> results;
549         try {
550             results = connectionInstance.transact(dbSchema, operations).get();
551         } catch (InterruptedException | ExecutionException e) {
552             LOG.warn("Ovsdb Not able to fetch OpenVswitch table row from device {}",
553                 connectionInstance.getConnectionInfo(), e);
554             return null;
555         }
556
557         return results == null || results.isEmpty() ? null
558                 : dbSchema.getTypedRowWrapper(OpenVSwitch.class, results.get(0).getRows().get(0));
559     }
560
561     private Entity getEntityFromConnectionInstance(@NonNull final OvsdbConnectionInstance ovsdbConnectionInstance) {
562         InstanceIdentifier<Node> iid = ovsdbConnectionInstance.getInstanceIdentifier();
563         if (iid == null) {
564             /* Switch initiated connection won't have iid, till it gets OpenVSwitch
565              * table update but update callback is always registered after ownership
566              * is granted. So we are explicitly fetch the row here to get the iid.
567              */
568             OpenVSwitch openvswitchRow = getOpenVswitchTableEntry(ovsdbConnectionInstance);
569             iid = SouthboundMapper.getInstanceIdentifier(instanceIdentifierCodec, openvswitchRow);
570             LOG.info("Ovsdb InstanceIdentifier {} generated for device "
571                     + "connection {}",iid,ovsdbConnectionInstance.getConnectionInfo());
572             ovsdbConnectionInstance.setInstanceIdentifier(iid);
573         }
574         Entity deviceEntity = new Entity(ENTITY_TYPE, iid);
575         LOG.debug("Ovsdb Entity {} created for device connection {}",
576                 deviceEntity, ovsdbConnectionInstance.getConnectionInfo());
577         return deviceEntity;
578     }
579
580     private OvsdbConnectionInstance getConnectionInstanceFromEntity(final Entity entity) {
581         return entityConnectionMap.get(entity);
582     }
583
584     private void registerEntityForOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
585         putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(), ovsdbConnectionInstance);
586
587         Entity candidateEntity = getEntityFromConnectionInstance(ovsdbConnectionInstance);
588         if (entityConnectionMap.containsKey(candidateEntity)) {
589             LOG.error("Ovsdb Old connection still hanging for {}", candidateEntity);
590             disconnected(ovsdbConnectionInstance.getOvsdbClient());
591             //TODO do cleanup for old connection or stale check
592         }
593         nodeIdVsConnectionInstance.put((InstanceIdentifier<Node>) candidateEntity.getIdentifier(),
594                 ovsdbConnectionInstance);
595         entityConnectionMap.put(candidateEntity, ovsdbConnectionInstance);
596         ovsdbConnectionInstance.setConnectedEntity(candidateEntity);
597         try {
598             EntityOwnershipCandidateRegistration registration =
599                     entityOwnershipService.registerCandidate(candidateEntity);
600             ovsdbConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
601             LOG.info("OVSDB entity {} is registered for ownership.", candidateEntity);
602
603         } catch (CandidateAlreadyRegisteredException e) {
604             LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
605         }
606         //If entity already has owner, it won't get notification from EntityOwnershipService
607         java.util.Optional<EntityOwnershipState> ownershipStateOpt =
608                 entityOwnershipService.getOwnershipState(candidateEntity);
609         if (ownershipStateOpt.isPresent()) {
610             EntityOwnershipState ownershipState = ownershipStateOpt.get();
611             if (ownershipState == EntityOwnershipState.OWNED_BY_OTHER) {
612                 ovsdbConnectionInstance.setHasDeviceOwnership(false);
613             } else if (ownershipState == EntityOwnershipState.IS_OWNER) {
614                 ovsdbConnectionInstance.setHasDeviceOwnership(true);
615                 ovsdbConnectionInstance.registerCallbacks(instanceIdentifierCodec);
616             }
617         }
618     }
619
620     private void unregisterEntityForOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
621         ovsdbConnectionInstance.closeDeviceOwnershipCandidateRegistration();
622         entityConnectionMap.remove(ovsdbConnectionInstance.getConnectedEntity(), ovsdbConnectionInstance);
623     }
624
625     private void retryConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode,
626                                  final ConnectionReconciliationTriggers trigger) {
627         final ReconciliationTask task = new ConnectionReconciliationTask(
628                 reconciliationManager,
629                 this,
630                 iid,
631                 ovsdbNode);
632
633         if (reconciliationManager.isEnqueued(task)) {
634             return;
635         }
636         switch (trigger) {
637             case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
638                 reconciliationManager.enqueueForRetry(task);
639                 break;
640             case ON_DISCONNECT: {
641                 CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture;
642                 try (ReadOnlyTransaction tx = db.newReadOnlyTransaction()) {
643                     readNodeFuture = tx.read(LogicalDatastoreType.CONFIGURATION, iid);
644                 }
645                 Futures.addCallback(readNodeFuture, new FutureCallback<Optional<Node>>() {
646                     @Override
647                     public void onSuccess(final Optional<Node> node) {
648                         if (node.isPresent()) {
649                             LOG.info("Disconnected/Failed connection {} was controller initiated, attempting "
650                                     + "reconnection", ovsdbNode.getConnectionInfo());
651                             reconciliationManager.enqueue(task);
652
653                         } else {
654                             LOG.debug("Connection {} was switch initiated, no reconciliation is required",
655                                     iid.firstKeyOf(Node.class).getNodeId());
656                         }
657                     }
658
659                     @Override
660                     public void onFailure(final Throwable throwable) {
661                         LOG.warn("Read Config/DS for Node failed! {}", iid, throwable);
662                     }
663                 }, MoreExecutors.directExecutor());
664                 break;
665             }
666             default:
667                 break;
668         }
669     }
670
671     public void reconcileBridgeConfigurations(final OvsdbConnectionInstance client) {
672         final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
673         final ReconciliationTask task = new BridgeConfigReconciliationTask(
674                 reconciliationManager, OvsdbConnectionManager.this, nodeIid, client, instanceIdentifierCodec);
675
676         reconciliationManager.enqueue(task);
677     }
678
679     private static class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
680         private final OvsdbConnectionManager cm;
681         private final EntityOwnershipListenerRegistration listenerRegistration;
682
683         OvsdbDeviceEntityOwnershipListener(final OvsdbConnectionManager cm,
684                 final EntityOwnershipService entityOwnershipService) {
685             this.cm = cm;
686             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
687         }
688
689         public void close() {
690             listenerRegistration.close();
691         }
692
693         @Override
694         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
695             cm.handleOwnershipChanged(ownershipChange);
696         }
697     }
698
699     private enum ConnectionReconciliationTriggers {
700         /*
701         Reconciliation trigger for scenario where controller's attempt
702         to connect to switch fails on config data store notification
703         */
704         ON_CONTROLLER_INITIATED_CONNECTION_FAILURE,
705
706         /*
707         Reconciliation trigger for the scenario where controller
708         initiated connection disconnects.
709         */
710         ON_DISCONNECT
711     }
712
713     public Map<ConnectionInfo, OvsdbConnectionInstance> getClients() {
714         return clients;
715     }
716 }