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