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