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