Migrate to use Objects.requireNonNull
[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 java.util.Objects.requireNonNull;
11 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
12
13 import com.google.common.annotations.VisibleForTesting;
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.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntryKey;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
64 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoCloseable {
69
70     private final Map<ConnectionInfo, OvsdbConnectionInstance> clients =
71             new ConcurrentHashMap<>();
72     private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionManager.class);
73     private static final String ENTITY_TYPE = "ovsdb";
74     private static final int DB_FETCH_TIMEOUT = 1000;
75
76     private final DataBroker db;
77     private final TransactionInvoker txInvoker;
78     private final Map<OvsdbClient, OvsdbClient> alreadyProcessedClients = new ConcurrentHashMap<>();
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         if (alreadyProcessedClients.containsKey(externalClient)) {
110             LOG.info("OvsdbConnectionManager Library already connected {} from {}:{} to {}:{} "
111                             + "to this, hence skipping the processing",
112                     externalClient.getConnectionInfo().getType(),
113                     externalClient.getConnectionInfo().getRemoteAddress(),
114                     externalClient.getConnectionInfo().getRemotePort(),
115                     externalClient.getConnectionInfo().getLocalAddress(),
116                     externalClient.getConnectionInfo().getLocalPort());
117             return;
118         }
119         alreadyProcessedClients.put(externalClient, externalClient);
120
121         LOG.info("OvsdbConnectionManager connected {} from {}:{} to {}:{}",
122                 externalClient.getConnectionInfo().getType(),
123                 externalClient.getConnectionInfo().getRemoteAddress(),
124                 externalClient.getConnectionInfo().getRemotePort(),
125                 externalClient.getConnectionInfo().getLocalAddress(),
126                 externalClient.getConnectionInfo().getLocalPort());
127         try {
128             List<String> databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
129             if (databases.contains(SouthboundConstants.OPEN_V_SWITCH)) {
130                 OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
131                 // Register Cluster Ownership for ConnectionInfo
132                 registerEntityForOwnership(client);
133                 OvsdbOperGlobalListener.runAfterTimeoutIfNodeNotCreated(client.getInstanceIdentifier(), () -> {
134                     externalClient.disconnect();
135                     disconnected(externalClient);
136                 });
137             }
138         } catch (InterruptedException | ExecutionException | TimeoutException e) {
139             LOG.warn("OvsdbConnectionManager Unable to fetch Database list from device {}."
140                     + "Disconnecting from the device.", externalClient.getConnectionInfo().getRemoteAddress(), e);
141             externalClient.disconnect();
142         }
143
144     }
145
146     public OvsdbConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
147         LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
148                 externalClient.getConnectionInfo().getRemotePort());
149         ConnectionInfo key = SouthboundMapper.createConnectionInfo(externalClient);
150         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
151
152         // Check if existing ovsdbConnectionInstance for the OvsdbClient present.
153         // In such cases, we will see if the ovsdbConnectionInstance has same externalClient.
154         if (ovsdbConnectionInstance != null) {
155             if (ovsdbConnectionInstance.hasOvsdbClient(externalClient)) {
156                 LOG.warn("OVSDB Connection Instance {} already exists for client {}", key, externalClient);
157                 return ovsdbConnectionInstance;
158             }
159             LOG.warn("OVSDB Connection Instance {} being replaced with client {}", key, externalClient);
160
161             // Unregister Cluster Ownership for ConnectionInfo
162             // Because the ovsdbConnectionInstance is about to be completely replaced!
163             unregisterEntityForOwnership(ovsdbConnectionInstance);
164
165             ovsdbConnectionInstance.disconnect();
166
167             removeConnectionInstance(key);
168
169             stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
170         }
171
172         ovsdbConnectionInstance = new OvsdbConnectionInstance(key, externalClient, txInvoker,
173                 getInstanceIdentifier(key));
174         ovsdbConnectionInstance.createTransactInvokers();
175         return ovsdbConnectionInstance;
176     }
177
178     @Override
179     public void disconnected(final OvsdbClient client) {
180         alreadyProcessedClients.remove(client);
181         LOG.info("Ovsdb Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
182                 client.getConnectionInfo().getType(),
183                 client.getConnectionInfo().getRemoteAddress(),
184                 client.getConnectionInfo().getRemotePort(),
185                 client.getConnectionInfo().getLocalAddress(),
186                 client.getConnectionInfo().getLocalPort());
187         ConnectionInfo key = SouthboundMapper.createConnectionInfo(client);
188         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
189         if (ovsdbConnectionInstance != null) {
190             // Unregister Entity ownership as soon as possible ,so this instance should
191             // not be used as a candidate in Entity election (given that this instance is
192             // about to disconnect as well), if current owner get disconnected from
193             // OVSDB device.
194             if (ovsdbConnectionInstance.getHasDeviceOwnership()) {
195                 LOG.info("Ovsdb Library disconnected {} this controller instance has ownership", key);
196                 deleteOperNodeAndReleaseOwnership(ovsdbConnectionInstance);
197             } else {
198                 LOG.info("Ovsdb Library disconnected {} this controller does not have ownership", key);
199                 unregisterEntityForOwnership(ovsdbConnectionInstance);
200             }
201             removeConnectionInstance(key);
202
203             //Controller initiated connection can be terminated from switch side.
204             //So cleanup the instance identifier cache.
205             removeInstanceIdentifier(key);
206             nodeIdVsConnectionInstance.remove(ovsdbConnectionInstance.getInstanceIdentifier(),
207                     ovsdbConnectionInstance);
208             stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
209             retryConnection(ovsdbConnectionInstance.getInstanceIdentifier(),
210                     ovsdbConnectionInstance.getOvsdbNodeAugmentation(),
211                     ConnectionReconciliationTriggers.ON_DISCONNECT);
212         } else {
213             LOG.warn("Ovsdb disconnected : Connection instance not found for OVSDB Node {} ", key);
214         }
215         LOG.trace("OvsdbConnectionManager: exit disconnected client: {}", client);
216     }
217
218     private void deleteOperNodeAndReleaseOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
219         ovsdbConnectionInstance.setHasDeviceOwnership(false);
220         final InstanceIdentifier nodeIid = ovsdbConnectionInstance.getInstanceIdentifier();
221         //remove the node from oper only if it has ownership
222         txInvoker.invoke(new OvsdbNodeRemoveCommand(ovsdbConnectionInstance, null, null) {
223
224             @Override
225             public void onSuccess() {
226                 super.onSuccess();
227                 LOG.debug("Successfully removed node {} from oper", nodeIid);
228                 //Giveup the ownership only after cleanup is done
229                 unregisterEntityForOwnership(ovsdbConnectionInstance);
230             }
231
232             @Override
233             public void onFailure(final Throwable throwable) {
234                 LOG.debug("Failed to remove node {} from oper", nodeIid);
235                 super.onFailure(throwable);
236                 unregisterEntityForOwnership(ovsdbConnectionInstance);
237             }
238         });
239     }
240
241     public OvsdbClient connect(final InstanceIdentifier<Node> iid,
242             final OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException, ConnectException {
243         LOG.info("Connecting to {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
244
245         // TODO handle case where we already have a connection
246         // TODO use transaction chains to handle ordering issues between disconnected
247         // TODO and connected when writing to the operational store
248         InetAddress ip = SouthboundMapper.createInetAddress(ovsdbNode.getConnectionInfo().getRemoteIp());
249         OvsdbClient client = ovsdbConnection.connect(ip,
250                 ovsdbNode.getConnectionInfo().getRemotePort().getValue().toJava());
251         // For connections from the controller to the ovs instance, the library doesn't call
252         // this method for us
253         if (client != null) {
254             putInstanceIdentifier(ovsdbNode.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
255             OvsdbConnectionInstance ovsdbConnectionInstance = connectedButCallBacksNotRegistered(client);
256             ovsdbConnectionInstance.setOvsdbNodeAugmentation(ovsdbNode);
257
258             // Register Cluster Ownership for ConnectionInfo
259             registerEntityForOwnership(ovsdbConnectionInstance);
260         } else {
261             LOG.warn("Failed to connect to OVSDB Node {}", ovsdbNode.getConnectionInfo());
262         }
263         return client;
264     }
265
266     public void disconnect(final OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
267         LOG.info("Disconnecting from {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
268         OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
269         if (client != null) {
270             // Unregister Cluster Onwership for ConnectionInfo
271             deleteOperNodeAndReleaseOwnership(client);
272
273             client.disconnect();
274
275             removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
276
277             stopBridgeConfigReconciliationIfActive(client.getInstanceIdentifier());
278         } else {
279             LOG.debug("disconnect : connection instance not found for {}",ovsdbNode.getConnectionInfo());
280         }
281     }
282
283 /*    public void init(ConnectionInfo key) {
284         OvsdbConnectionInstance client = getConnectionInstance(key);
285
286         // TODO (FF): make sure that this cluster instance is the 'entity owner' fo the given OvsdbConnectionInstance ?
287
288         if (client != null) {
289
290              *  Note: registerCallbacks() is idemPotent... so if you call it repeatedly all is safe,
291              *  it only registersCallbacks on the *first* call.
292
293             client.registerCallbacks();
294         }
295     }
296 */
297     @Override
298     public void close() {
299         if (ovsdbDeviceEntityOwnershipListener != null) {
300             ovsdbDeviceEntityOwnershipListener.close();
301         }
302
303         for (OvsdbConnectionInstance client: clients.values()) {
304             client.disconnect();
305         }
306     }
307
308     @VisibleForTesting
309     void putConnectionInstance(final ConnectionInfo key,final OvsdbConnectionInstance instance) {
310         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
311         clients.put(connectionInfo, instance);
312     }
313
314     private void removeConnectionInstance(final ConnectionInfo key) {
315         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
316         clients.remove(connectionInfo);
317     }
318
319     @VisibleForTesting
320     void putInstanceIdentifier(final ConnectionInfo key, final InstanceIdentifier<Node> iid) {
321         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
322         instanceIdentifiers.put(connectionInfo, iid);
323     }
324
325     private void removeInstanceIdentifier(final ConnectionInfo key) {
326         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
327         instanceIdentifiers.remove(connectionInfo);
328     }
329
330     public InstanceIdentifier<Node> getInstanceIdentifier(final ConnectionInfo key) {
331         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
332         return instanceIdentifiers.get(connectionInfo);
333     }
334
335     public OvsdbConnectionInstance getConnectionInstance(final ConnectionInfo key) {
336         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
337         return clients.get(connectionInfo);
338     }
339
340     public OvsdbConnectionInstance getConnectionInstance(final OvsdbBridgeAttributes mn) {
341         Optional<OvsdbNodeAugmentation> optional = SouthboundUtil.getManagingNode(db, mn);
342         if (optional.isPresent()) {
343             return getConnectionInstance(optional.get().getConnectionInfo());
344         } else {
345             return null;
346         }
347     }
348
349     public OvsdbConnectionInstance getConnectionInstance(final Node node) {
350         requireNonNull(node);
351         OvsdbNodeAugmentation ovsdbNode = node.augmentation(OvsdbNodeAugmentation.class);
352         OvsdbBridgeAugmentation ovsdbManagedNode = node.augmentation(OvsdbBridgeAugmentation.class);
353         if (ovsdbNode != null) {
354             return getConnectionInstance(ovsdbNode.getConnectionInfo());
355         } else if (ovsdbManagedNode != null) {
356             return getConnectionInstance(ovsdbManagedNode);
357         } else {
358             LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
359             return null;
360         }
361     }
362
363     public OvsdbConnectionInstance getConnectionInstance(final InstanceIdentifier<Node> nodePath) {
364         if (nodeIdVsConnectionInstance.get(nodePath) != null) {
365             return nodeIdVsConnectionInstance.get(nodePath);
366         }
367         try {
368             ReadTransaction transaction = db.newReadOnlyTransaction();
369             FluentFuture<Optional<Node>> nodeFuture = transaction.read(
370                     LogicalDatastoreType.OPERATIONAL, nodePath);
371             transaction.close();
372             Optional<Node> optional = nodeFuture.get();
373             if (optional.isPresent()) {
374                 return this.getConnectionInstance(optional.get());
375             } else {
376                 LOG.debug("Node was not found on the path in the operational DS: {}", nodePath);
377                 return null;
378             }
379         } catch (InterruptedException | ExecutionException e) {
380             LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
381             return null;
382         }
383     }
384
385     public OvsdbClient getClient(final ConnectionInfo connectionInfo) {
386         OvsdbConnectionInstance connectionInstance = getConnectionInstance(connectionInfo);
387         if (connectionInstance != null) {
388             return connectionInstance.getOvsdbClient();
389         }
390         return null;
391     }
392
393     public OvsdbClient getClient(final OvsdbBridgeAttributes mn) {
394         return getConnectionInstance(mn).getOvsdbClient();
395     }
396
397     public OvsdbClient getClient(final Node node) {
398         return getConnectionInstance(node).getOvsdbClient();
399     }
400
401     public Boolean getHasDeviceOwnership(final ConnectionInfo connectionInfo) {
402         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(connectionInfo);
403         if (ovsdbConnectionInstance == null) {
404             return Boolean.FALSE;
405         }
406         return ovsdbConnectionInstance.getHasDeviceOwnership();
407     }
408
409     public void reconcileConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode) {
410         this.retryConnection(iid, ovsdbNode,
411                 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
412
413     }
414
415     public void stopConnectionReconciliationIfActive(final InstanceIdentifier<Node> iid,
416             final OvsdbNodeAugmentation ovsdbNode) {
417         final ReconciliationTask task = new ConnectionReconciliationTask(
418                 reconciliationManager,
419                 this,
420                 iid,
421                 ovsdbNode);
422         reconciliationManager.dequeue(task);
423     }
424
425     public void stopBridgeConfigReconciliationIfActive(final InstanceIdentifier<Node> iid) {
426         final ReconciliationTask task =
427                 new BridgeConfigReconciliationTask(reconciliationManager, this, iid, null, instanceIdentifierCodec);
428         reconciliationManager.dequeue(task);
429         reconciliationManager.cancelTerminationPointReconciliation();
430     }
431
432     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
433             justification = "https://github.com/spotbugs/spotbugs/issues/811")
434     private void handleOwnershipChanged(final EntityOwnershipChange ownershipChange) {
435         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
436         LOG.debug("Ovsdb handleOwnershipChanged: {} event received for device {}",
437                 ownershipChange, ovsdbConnectionInstance != null ? ovsdbConnectionInstance.getConnectionInfo()
438                         : "that's currently NOT registered by *this* southbound plugin instance");
439
440         if (ovsdbConnectionInstance == null) {
441             if (ownershipChange.getState().isOwner()) {
442                 LOG.warn("Ovsdb handleOwnershipChanged: *this* instance is elected as an owner of the device {} but it "
443                         + "is NOT registered for ownership", ownershipChange.getEntity());
444             } else {
445                 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
446                 // that instance registered for the device ownership or not. It is to make sure that
447                 // If all the controller instance that was connected to the device are down, so the
448                 // running instance can clear up the operational data store even though it was not
449                 // connected to the device.
450                 LOG.debug("Ovsdb handleOwnershipChanged: No connection instance found for {}",
451                     ownershipChange.getEntity());
452             }
453
454             // If entity has no owner, clean up the operational data store (it's possible because owner controller
455             // might went down abruptly and didn't get a chance to clean up the operational data store.
456             if (!ownershipChange.getState().hasOwner()) {
457                 LOG.info("Ovsdb {} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
458                 cleanEntityOperationalData(ownershipChange.getEntity());
459             }
460             return;
461         }
462         //Connection detail need to be cached, irrespective of ownership result.
463         putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
464
465         if (ownershipChange.getState().isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
466             LOG.info("Ovsdb handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
467                     ovsdbConnectionInstance.getConnectionInfo(), ovsdbConnectionInstance.getHasDeviceOwnership()
468                             ? SouthboundConstants.OwnershipStates.OWNER.getState()
469                             : SouthboundConstants.OwnershipStates.NONOWNER.getState());
470             return;
471         }
472
473         ovsdbConnectionInstance.setHasDeviceOwnership(ownershipChange.getState().isOwner());
474         // You were not an owner, but now you are
475         if (ownershipChange.getState().isOwner()) {
476             LOG.info("Ovsdb handleOwnershipChanged: *this* southbound plugin instance is an OWNER of the device {}",
477                     ovsdbConnectionInstance.getConnectionInfo());
478
479             //*this* instance of southbound plugin is owner of the device,
480             //so register for monitor callbacks
481             ovsdbConnectionInstance.registerCallbacks(instanceIdentifierCodec);
482             LOG.trace("Ovsdb isUpgradeInProgress {}", upgradeState.isUpgradeInProgress());
483             if (!upgradeState.isUpgradeInProgress()) {
484                 reconcileBridgeConfigurations(ovsdbConnectionInstance);
485             }
486         } else {
487             //You were owner of the device, but now you are not. With the current ownership
488             //grant mechanism, this scenario should not occur. Because this scenario will occur
489             //when this controller went down or switch flap the connection, but in both the case
490             //it will go through the re-registration process. We need to implement this condition
491             //when clustering service implement a ownership grant strategy which can revoke the
492             //device ownership for load balancing the devices across the instances.
493             //Once this condition occur, we should unregister the callback.
494             LOG.error("Ovsdb handleOwnershipChanged: *this* southbound plugin instance is no longer"
495                     + " the owner of device {}.This should NOT happen.",
496                     ovsdbConnectionInstance.getNodeId().getValue());
497         }
498     }
499
500     private void cleanEntityOperationalData(final Entity entity) {
501
502         //Do explicit cleanup rather than using OvsdbNodeRemoveCommand, because there
503         // are chances that other controller instance went down abruptly and it does
504         // not clear manager entry, which OvsdbNodeRemoveCommand look for before cleanup.
505
506         @SuppressWarnings("unchecked")
507         final InstanceIdentifier<Node> nodeIid = (InstanceIdentifier<Node>) entity.getIdentifier();
508
509         txInvoker.invoke(transaction -> {
510             Optional<Node> ovsdbNodeOpt = SouthboundUtil.readNode(transaction, nodeIid);
511             if (ovsdbNodeOpt.isPresent()) {
512                 Node ovsdbNode = ovsdbNodeOpt.get();
513                 OvsdbNodeAugmentation nodeAugmentation = ovsdbNode.augmentation(OvsdbNodeAugmentation.class);
514                 if (nodeAugmentation != null) {
515                     Map<ManagedNodeEntryKey, ManagedNodeEntry> entries = nodeAugmentation.getManagedNodeEntry();
516                     if (entries != null) {
517                         for (ManagedNodeEntry managedNode : entries.values()) {
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                 FluentFuture<Boolean> readNodeFuture;
642                 try (ReadTransaction tx = db.newReadOnlyTransaction()) {
643                     readNodeFuture = tx.exists(LogicalDatastoreType.CONFIGURATION, iid);
644                 }
645                 readNodeFuture.addCallback(new FutureCallback<Boolean>() {
646                     @Override
647                     public void onSuccess(final Boolean node) {
648                         if (node.booleanValue()) {
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 }