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