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