Merge "Bug 6304 - Regression in Connection reconciliation functionality"
[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     }
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.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.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.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.isOwner());
412         // You were not an owner, but now you are
413         if (ownershipChange.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();
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") final InstanceIdentifier<Node> nodeIid =
443                 (InstanceIdentifier<Node>) SouthboundUtil
444                         .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
445
446         txInvoker.invoke(new TransactionCommand() {
447             @Override
448             public void execute(ReadWriteTransaction transaction) {
449                 Optional<Node> ovsdbNodeOpt = SouthboundUtil.readNode(transaction, nodeIid);
450                 if (ovsdbNodeOpt.isPresent()) {
451                     Node ovsdbNode = ovsdbNodeOpt.get();
452                     OvsdbNodeAugmentation nodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
453                     if (nodeAugmentation != null) {
454                         if (nodeAugmentation.getManagedNodeEntry() != null) {
455                             for (ManagedNodeEntry managedNode : nodeAugmentation.getManagedNodeEntry()) {
456                                 transaction.delete(
457                                         LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
458                             }
459                         } else {
460                             LOG.debug("{} had no managed nodes", ovsdbNode.getNodeId().getValue());
461                         }
462                     }
463                     transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
464                 }
465             }
466         });
467
468     }
469
470     private OpenVSwitch getOpenVswitchTableEntry(OvsdbConnectionInstance connectionInstance) {
471         DatabaseSchema dbSchema = null;
472         OpenVSwitch openVSwitchRow = null;
473         try {
474             dbSchema = connectionInstance.getSchema(OvsdbSchemaContants.DATABASE_NAME).get();
475         } catch (InterruptedException | ExecutionException e) {
476             LOG.warn("Not able to fetch schema for database {} from device {}",
477                     OvsdbSchemaContants.DATABASE_NAME,connectionInstance.getConnectionInfo(),e);
478         }
479         if (dbSchema != null) {
480             GenericTableSchema openVSwitchSchema = TyperUtils.getTableSchema(dbSchema, OpenVSwitch.class);
481
482             List<String> openVSwitchTableColumn = new ArrayList<>();
483             openVSwitchTableColumn.addAll(openVSwitchSchema.getColumns());
484             Select<GenericTableSchema> selectOperation = op.select(openVSwitchSchema);
485             selectOperation.setColumns(openVSwitchTableColumn);
486
487             List<Operation> operations = new ArrayList<>();
488             operations.add(selectOperation);
489             operations.add(op.comment("Fetching Open_VSwitch table rows"));
490             try {
491                 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
492                 if (results != null ) {
493                     OperationResult selectResult = results.get(0);
494                     openVSwitchRow = TyperUtils.getTypedRowWrapper(
495                             dbSchema,OpenVSwitch.class,selectResult.getRows().get(0));
496
497                 }
498             } catch (InterruptedException | ExecutionException e) {
499                 LOG.warn("Not able to fetch OpenVswitch table row from device {}",
500                         connectionInstance.getConnectionInfo(),e);
501             }
502         }
503         return openVSwitchRow;
504     }
505
506     private Entity getEntityFromConnectionInstance(@Nonnull OvsdbConnectionInstance ovsdbConnectionInstance) {
507         InstanceIdentifier<Node> iid = ovsdbConnectionInstance.getInstanceIdentifier();
508         if ( iid == null ) {
509             /* Switch initiated connection won't have iid, till it gets OpenVSwitch
510              * table update but update callback is always registered after ownership
511              * is granted. So we are explicitly fetch the row here to get the iid.
512              */
513             OpenVSwitch openvswitchRow = getOpenVswitchTableEntry(ovsdbConnectionInstance);
514             iid = SouthboundMapper.getInstanceIdentifier(openvswitchRow);
515             LOG.info("InstanceIdentifier {} generated for device "
516                     + "connection {}",iid,ovsdbConnectionInstance.getConnectionInfo());
517             ovsdbConnectionInstance.setInstanceIdentifier(iid);
518         }
519         YangInstanceIdentifier entityId = SouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
520         Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
521         LOG.debug("Entity {} created for device connection {}",
522                 deviceEntity, ovsdbConnectionInstance.getConnectionInfo());
523         return deviceEntity;
524     }
525
526     private OvsdbConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
527         return entityConnectionMap.get(entity);
528     }
529
530     private void registerEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
531
532         Entity candidateEntity = getEntityFromConnectionInstance(ovsdbConnectionInstance);
533         entityConnectionMap.put(candidateEntity, ovsdbConnectionInstance);
534         ovsdbConnectionInstance.setConnectedEntity(candidateEntity);
535         try {
536             EntityOwnershipCandidateRegistration registration =
537                     entityOwnershipService.registerCandidate(candidateEntity);
538             ovsdbConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
539             LOG.info("OVSDB entity {} is registered for ownership.", candidateEntity);
540
541             //If entity already has owner, it won't get notification from EntityOwnershipService
542             //so cache the connection instances.
543             Optional<EntityOwnershipState> ownershipStateOpt =
544                     entityOwnershipService.getOwnershipState(candidateEntity);
545             if (ownershipStateOpt.isPresent()) {
546                 EntityOwnershipState ownershipState = ownershipStateOpt.get();
547                 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
548                     LOG.info("OVSDB entity {} is already owned by other southbound plugin "
549                                     + "instance, so *this* instance is NOT an OWNER of the device",
550                             ovsdbConnectionInstance.getConnectionInfo());
551                     putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
552                 }
553             }
554         } catch (CandidateAlreadyRegisteredException e) {
555             LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
556         }
557
558     }
559
560     private void unregisterEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
561         ovsdbConnectionInstance.closeDeviceOwnershipCandidateRegistration();
562         entityConnectionMap.remove(ovsdbConnectionInstance.getConnectedEntity());
563     }
564
565     private void retryConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode,
566                                  ConnectionReconciliationTriggers trigger) {
567         final ReconciliationTask task = new ConnectionReconciliationTask(
568                 reconciliationManager,
569                 this,
570                 iid,
571                 ovsdbNode);
572
573         if (reconciliationManager.isEnqueued(task)) {
574             return;
575         }
576         switch (trigger) {
577             case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
578                 reconciliationManager.enqueueForRetry(task);
579                 break;
580             case ON_DISCONNECT:
581             {
582                 ReadOnlyTransaction tx = db.newReadOnlyTransaction();
583                 CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture =
584                         tx.read(LogicalDatastoreType.CONFIGURATION, iid);
585
586                 final OvsdbConnectionManager connectionManager = this;
587                 Futures.addCallback(readNodeFuture, new FutureCallback<Optional<Node>>() {
588                     @Override
589                     public void onSuccess(@Nullable Optional<Node> node) {
590                         if (node.isPresent()) {
591                             LOG.info("Disconnected/Failed connection {} was controller initiated, attempting "
592                                     + "reconnection", ovsdbNode.getConnectionInfo());
593                             reconciliationManager.enqueue(task);
594
595                         } else {
596                             LOG.debug("Connection {} was switch initiated, no reconciliation is required",
597                                     iid.firstKeyOf(Node.class).getNodeId());
598                         }
599                     }
600
601                     @Override
602                     public void onFailure(Throwable throwable) {
603                         LOG.warn("Read Config/DS for Node failed! {}", iid, throwable);
604                     }
605                 });
606                 break;
607             }
608             default:
609                 break;
610         }
611     }
612
613     private void reconcileBridgeConfigurations(final OvsdbConnectionInstance client) {
614         final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
615         final ReconciliationTask task = new BridgeConfigReconciliationTask(
616                 reconciliationManager, OvsdbConnectionManager.this, nodeIid, client);
617
618         reconciliationManager.enqueue(task);
619     }
620
621     private class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
622         private OvsdbConnectionManager cm;
623         private EntityOwnershipListenerRegistration listenerRegistration;
624
625         OvsdbDeviceEntityOwnershipListener(OvsdbConnectionManager cm, EntityOwnershipService entityOwnershipService) {
626             this.cm = cm;
627             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
628         }
629
630         public void close() {
631             listenerRegistration.close();
632         }
633
634         @Override
635         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
636             cm.handleOwnershipChanged(ownershipChange);
637         }
638     }
639
640     private enum ConnectionReconciliationTriggers {
641         /*
642         Reconciliation trigger for scenario where controller's attempt
643         to connect to switch fails on config data store notification
644         */
645         ON_CONTROLLER_INITIATED_CONNECTION_FAILURE,
646
647         /*
648         Reconciliation trigger for the scenario where controller
649         initiated connection disconnects.
650         */
651         ON_DISCONNECT
652     }
653 }