Migrate TyperUtils.getTableSchema() users
[ovsdb.git] / hwvtepsouthbound / hwvtepsouthbound-impl / src / main / java / org / opendaylight / ovsdb / hwvtepsouthbound / HwvtepConnectionManager.java
1 /*
2  * Copyright (c) 2015, 2018 Ericsson India Global Services Pvt Ltd. 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
9 package org.opendaylight.ovsdb.hwvtepsouthbound;
10
11 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
12
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.net.ConnectException;
20 import java.net.InetAddress;
21 import java.net.UnknownHostException;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
32 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
33 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
34 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
35 import org.opendaylight.mdsal.eos.binding.api.Entity;
36 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
37 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
38 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
39 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
40 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
41 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
42 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
43 import org.opendaylight.ovsdb.hwvtepsouthbound.events.ClientConnected;
44 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.ReconciliationManager;
45 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.ReconciliationTask;
46 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.configuration.HwvtepReconciliationTask;
47 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.connection.ConnectionReconciliationTask;
48 import org.opendaylight.ovsdb.hwvtepsouthbound.transact.DependencyQueue;
49 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.HwvtepGlobalRemoveCommand;
50 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvoker;
51 import org.opendaylight.ovsdb.lib.OvsdbClient;
52 import org.opendaylight.ovsdb.lib.OvsdbConnection;
53 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
54 import org.opendaylight.ovsdb.lib.operations.Operation;
55 import org.opendaylight.ovsdb.lib.operations.OperationResult;
56 import org.opendaylight.ovsdb.lib.operations.Select;
57 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
58 import org.opendaylight.ovsdb.lib.schema.typed.TypedDatabaseSchema;
59 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
60 import org.opendaylight.ovsdb.schema.hardwarevtep.Global;
61 import org.opendaylight.ovsdb.utils.mdsal.utils.TransactionHistory;
62 import org.opendaylight.ovsdb.utils.mdsal.utils.TransactionType;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalSwitchAttributes;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.PhysicalSwitchAugmentation;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ConnectionInfo;
67 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
68 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71
72 public class HwvtepConnectionManager implements OvsdbConnectionListener, AutoCloseable {
73     private final Map<ConnectionInfo, HwvtepConnectionInstance> clients = new ConcurrentHashMap<>();
74     private static final Logger LOG = LoggerFactory.getLogger(HwvtepConnectionManager.class);
75     private static final String ENTITY_TYPE = "hwvtep";
76     private static final int DB_FETCH_TIMEOUT = 1000;
77     private static final int TRANSACTION_HISTORY_CAPACITY = 10000;
78     private static final int TRANSACTION_HISTORY_WATERMARK = 7500;
79
80     private final DataBroker db;
81     private final TransactionInvoker txInvoker;
82     private final Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers = new ConcurrentHashMap<>();
83     private final Map<Entity, HwvtepConnectionInstance> entityConnectionMap = new ConcurrentHashMap<>();
84     private final EntityOwnershipService entityOwnershipService;
85     private final HwvtepDeviceEntityOwnershipListener hwvtepDeviceEntityOwnershipListener;
86     private final ReconciliationManager reconciliationManager;
87     private final Map<InstanceIdentifier<Node>, HwvtepConnectionInstance> nodeIidVsConnectionInstance =
88             new ConcurrentHashMap<>();
89     private final HwvtepOperGlobalListener hwvtepOperGlobalListener;
90     private final Map<InstanceIdentifier<Node>, TransactionHistory> controllerTxHistory = new ConcurrentHashMap<>();
91     private final Map<InstanceIdentifier<Node>, TransactionHistory> deviceUpdateHistory = new ConcurrentHashMap<>();
92     private final OvsdbConnection ovsdbConnectionService;
93
94     public HwvtepConnectionManager(final DataBroker db, final TransactionInvoker txInvoker,
95                     final EntityOwnershipService entityOwnershipService, final OvsdbConnection ovsdbConnectionService) {
96         this.db = db;
97         this.txInvoker = txInvoker;
98         this.entityOwnershipService = entityOwnershipService;
99         this.hwvtepDeviceEntityOwnershipListener = new HwvtepDeviceEntityOwnershipListener(this,entityOwnershipService);
100         this.reconciliationManager = new ReconciliationManager(db);
101         this.hwvtepOperGlobalListener = new HwvtepOperGlobalListener(db, this);
102         this.ovsdbConnectionService = ovsdbConnectionService;
103     }
104
105     @Override
106     public void close() throws Exception {
107         if (hwvtepDeviceEntityOwnershipListener != null) {
108             hwvtepDeviceEntityOwnershipListener.close();
109         }
110
111         for (HwvtepConnectionInstance client: clients.values()) {
112             client.disconnect();
113         }
114         DependencyQueue.close();
115     }
116
117     @Override
118     public void connected(final OvsdbClient externalClient) {
119         LOG.info("Library connected {} from {}:{} to {}:{}",
120                 externalClient.getConnectionInfo().getType(),
121                 externalClient.getConnectionInfo().getRemoteAddress(),
122                 externalClient.getConnectionInfo().getRemotePort(),
123                 externalClient.getConnectionInfo().getLocalAddress(),
124                 externalClient.getConnectionInfo().getLocalPort());
125         try {
126             List<String> databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
127             if (databases.contains(HwvtepSchemaConstants.HARDWARE_VTEP)) {
128                 HwvtepConnectionInstance hwClient = connectedButCallBacksNotRegistered(externalClient);
129                 registerEntityForOwnership(hwClient);
130             }
131         } catch (InterruptedException | ExecutionException | TimeoutException e) {
132             LOG.warn("Unable to fetch Database list from device {}. Disconnecting from the device.",
133                     externalClient.getConnectionInfo().getRemoteAddress(), e);
134             externalClient.disconnect();
135         }
136     }
137
138     @Override
139     public void disconnected(final OvsdbClient client) {
140         LOG.info("Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
141                 client.getConnectionInfo().getType(),
142                 client.getConnectionInfo().getRemoteAddress(),
143                 client.getConnectionInfo().getRemotePort(),
144                 client.getConnectionInfo().getLocalAddress(),
145                 client.getConnectionInfo().getLocalPort());
146         ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(client);
147         HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
148         if (hwvtepConnectionInstance != null) {
149             if (hwvtepConnectionInstance.getInstanceIdentifier() != null) {
150                 deviceUpdateHistory.get(hwvtepConnectionInstance.getInstanceIdentifier()).addToHistory(
151                         TransactionType.DELETE, new ClientConnected(client.getConnectionInfo().getRemotePort()));
152             }
153
154
155             // Unregister Entity ownership as soon as possible ,so this instance should
156             // not be used as a candidate in Entity election (given that this instance is
157             // about to disconnect as well), if current owner get disconnected from
158             // HWVTEP device.
159             if (hwvtepConnectionInstance.getHasDeviceOwnership()) {
160                 unregisterEntityForOwnership(hwvtepConnectionInstance);
161                 txInvoker.invoke(new HwvtepGlobalRemoveCommand(hwvtepConnectionInstance, null, null));
162             } else {
163                 unregisterEntityForOwnership(hwvtepConnectionInstance);
164                 //Do not delete if client disconnected from follower HwvtepGlobalRemoveCommand
165             }
166
167             removeConnectionInstance(key);
168
169             //Controller initiated connection can be terminated from switch side.
170             //So cleanup the instance identifier cache.
171             removeInstanceIdentifier(key);
172             removeConnectionInstance(hwvtepConnectionInstance.getInstanceIdentifier());
173             retryConnection(hwvtepConnectionInstance.getInstanceIdentifier(),
174                     hwvtepConnectionInstance.getHwvtepGlobalAugmentation(),
175                     ConnectionReconciliationTriggers.ON_DISCONNECT);
176         } else {
177             LOG.warn("HWVTEP disconnected event did not find connection instance for {}", key);
178         }
179         LOG.trace("HwvtepConnectionManager exit disconnected client: {}", client);
180     }
181
182     public OvsdbClient connect(final InstanceIdentifier<Node> iid, final HwvtepGlobalAugmentation hwvtepGlobal)
183             throws UnknownHostException, ConnectException {
184         LOG.info("Connecting to {}", HwvtepSouthboundUtil.connectionInfoToString(hwvtepGlobal.getConnectionInfo()));
185         InetAddress ip = HwvtepSouthboundMapper.createInetAddress(hwvtepGlobal.getConnectionInfo().getRemoteIp());
186         OvsdbClient client = ovsdbConnectionService
187                         .connect(ip, hwvtepGlobal.getConnectionInfo().getRemotePort().getValue().toJava());
188         if (client != null) {
189             putInstanceIdentifier(hwvtepGlobal.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
190             HwvtepConnectionInstance hwvtepConnectionInstance = connectedButCallBacksNotRegistered(client);
191             hwvtepConnectionInstance.setHwvtepGlobalAugmentation(hwvtepGlobal);
192             hwvtepConnectionInstance.setInstanceIdentifier(iid.firstIdentifierOf(Node.class));
193
194             // Register Cluster Ownership for ConnectionInfo
195             registerEntityForOwnership(hwvtepConnectionInstance);
196         } else {
197             LOG.warn("Failed to connect to OVSDB node: {}", hwvtepGlobal.getConnectionInfo());
198         }
199         return client;
200     }
201
202     public void disconnect(final HwvtepGlobalAugmentation ovsdbNode) throws UnknownHostException {
203         LOG.info("Diconnecting from {}", HwvtepSouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
204         HwvtepConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
205         if (client != null) {
206             client.disconnect();
207             // Unregister Cluster Ownership for ConnectionInfo
208             unregisterEntityForOwnership(client);
209             removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
210         }
211     }
212
213     public HwvtepConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
214         LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
215                 externalClient.getConnectionInfo().getRemotePort());
216         ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(externalClient);
217         HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
218
219         // Check if existing hwvtepConnectionInstance for the OvsdbClient present.
220         // In such cases, we will see if the hwvtepConnectionInstance has same externalClient.
221         if (hwvtepConnectionInstance != null) {
222             if (hwvtepConnectionInstance.hasOvsdbClient(externalClient)) {
223                 LOG.warn("HWVTEP Connection Instance {} already exists for client {}", key, externalClient);
224                 return hwvtepConnectionInstance;
225             }
226             LOG.warn("HWVTEP Connection Instance {} being replaced with client {}", key, externalClient);
227             hwvtepConnectionInstance.disconnect();
228
229             // Unregister Cluster Ownership for ConnectionInfo
230             // Because the hwvtepConnectionInstance is about to be completely replaced!
231             unregisterEntityForOwnership(hwvtepConnectionInstance);
232
233             removeConnectionInstance(key);
234         }
235
236         hwvtepConnectionInstance = new HwvtepConnectionInstance(this, key, externalClient, getInstanceIdentifier(key),
237                 txInvoker, db);
238         hwvtepConnectionInstance.createTransactInvokers();
239         return hwvtepConnectionInstance;
240     }
241
242     private void putConnectionInstance(final ConnectionInfo key,final HwvtepConnectionInstance instance) {
243         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
244         clients.put(connectionInfo, instance);
245         LOG.info("Clients after put: {}", clients);
246     }
247
248     void putConnectionInstance(final InstanceIdentifier<Node> nodeIid,
249             final HwvtepConnectionInstance connectionInstance) {
250         nodeIidVsConnectionInstance.put(nodeIid, connectionInstance);
251     }
252
253     public HwvtepConnectionInstance getConnectionInstanceFromNodeIid(final InstanceIdentifier<Node> nodeIid) {
254         HwvtepConnectionInstance hwvtepConnectionInstance = nodeIidVsConnectionInstance.get(nodeIid);
255         if (hwvtepConnectionInstance != null) {
256             return hwvtepConnectionInstance;
257         }
258         InstanceIdentifier<Node> globalNodeIid = HwvtepSouthboundUtil.getGlobalNodeIid(nodeIid);
259         if (globalNodeIid != null) {
260             return nodeIidVsConnectionInstance.get(globalNodeIid);
261         }
262         return null;
263     }
264
265     public HwvtepConnectionInstance getConnectionInstance(final ConnectionInfo key) {
266         if (key == null) {
267             return null;
268         }
269         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
270         return clients.get(connectionInfo);
271     }
272
273     public HwvtepConnectionInstance getConnectionInstance(final Node node) {
274         Preconditions.checkNotNull(node);
275         HwvtepGlobalAugmentation hwvtepGlobal = node.augmentation(HwvtepGlobalAugmentation.class);
276         PhysicalSwitchAugmentation switchNode = node.augmentation(PhysicalSwitchAugmentation.class);
277         if (hwvtepGlobal != null) {
278             if (hwvtepGlobal.getConnectionInfo() != null) {
279                 return getConnectionInstance(hwvtepGlobal.getConnectionInfo());
280             } else {
281                 //TODO: Case of user configured connection for now
282                 //TODO: We could get it from Managers also.
283                 return null;
284             }
285         }
286         else if (switchNode != null) {
287             return getConnectionInstance(switchNode);
288         } else {
289             LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
290             return null;
291         }
292     }
293
294     public HwvtepConnectionInstance getConnectionInstance(final HwvtepPhysicalSwitchAttributes node) {
295         Optional<HwvtepGlobalAugmentation> optional = HwvtepSouthboundUtil.getManagingNode(db, node);
296         if (optional.isPresent()) {
297             return getConnectionInstance(optional.get().getConnectionInfo());
298         } else {
299             return null;
300         }
301     }
302
303     public void stopConfigurationReconciliation(final InstanceIdentifier<Node> nodeIid) {
304         final ReconciliationTask task = new HwvtepReconciliationTask(
305                 reconciliationManager, HwvtepConnectionManager.this, nodeIid, null, null, db);
306
307         reconciliationManager.dequeue(task);
308     }
309
310     public void reconcileConfigurations(final HwvtepConnectionInstance client, final Node psNode) {
311         final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
312         final ReconciliationTask task = new HwvtepReconciliationTask(
313                 reconciliationManager, HwvtepConnectionManager.this, nodeIid, psNode, client, db);
314
315         reconciliationManager.enqueue(task);
316     }
317
318     private void removeConnectionInstance(final ConnectionInfo key) {
319         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
320         clients.remove(connectionInfo);
321         LOG.info("Clients after remove: {}", clients);
322     }
323
324     private void removeConnectionInstance(final InstanceIdentifier<Node> nodeIid) {
325         if (nodeIid != null) {
326             nodeIidVsConnectionInstance.remove(nodeIid);
327         }
328     }
329
330     private void putInstanceIdentifier(final ConnectionInfo key,final InstanceIdentifier<Node> iid) {
331         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
332         instanceIdentifiers.put(connectionInfo, iid);
333     }
334
335     public InstanceIdentifier<Node> getInstanceIdentifier(final ConnectionInfo key) {
336         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
337         return instanceIdentifiers.get(connectionInfo);
338     }
339
340     private void removeInstanceIdentifier(final ConnectionInfo key) {
341         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
342         instanceIdentifiers.remove(connectionInfo);
343     }
344
345     public OvsdbClient getClient(final ConnectionInfo connectionInfo) {
346         return getConnectionInstance(connectionInfo).getOvsdbClient();
347     }
348
349     private void registerEntityForOwnership(final HwvtepConnectionInstance hwvtepConnectionInstance) {
350
351         Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
352         if (entityConnectionMap.get(candidateEntity) != null) {
353             disconnected(entityConnectionMap.get(candidateEntity).getOvsdbClient());
354             putConnectionInstance(hwvtepConnectionInstance.getInstanceIdentifier(), hwvtepConnectionInstance);
355         }
356         entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
357         hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
358
359         try {
360             EntityOwnershipCandidateRegistration registration =
361                     entityOwnershipService.registerCandidate(candidateEntity);
362             hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
363             LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
364
365             //If entity already has owner, it won't get notification from EntityOwnershipService
366             //so cache the connection instances.
367             handleOwnershipState(candidateEntity, hwvtepConnectionInstance);
368         } catch (CandidateAlreadyRegisteredException e) {
369             LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
370         }
371
372     }
373
374     private void handleOwnershipState(final Entity candidateEntity,
375             final HwvtepConnectionInstance hwvtepConnectionInstance) {
376         //If entity already has owner, it won't get notification from EntityOwnershipService
377         //so cache the connection instances.
378         java.util.Optional<EntityOwnershipState> ownershipStateOpt =
379                 entityOwnershipService.getOwnershipState(candidateEntity);
380         if (ownershipStateOpt.isPresent()) {
381             EntityOwnershipState ownershipState = ownershipStateOpt.get();
382             putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(), hwvtepConnectionInstance);
383             if (ownershipState != EntityOwnershipState.NO_OWNER) {
384                 hwvtepConnectionInstance.setHasDeviceOwnership(ownershipState == EntityOwnershipState.IS_OWNER);
385                 if (ownershipState != EntityOwnershipState.IS_OWNER) {
386                     LOG.info("HWVTEP entity {} is already owned by other southbound plugin "
387                                     + "instance, so *this* instance is NOT an OWNER of the device",
388                             hwvtepConnectionInstance.getConnectionInfo());
389                 } else {
390                     afterTakingOwnership(hwvtepConnectionInstance);
391                 }
392             }
393         }
394     }
395
396     private void afterTakingOwnership(final HwvtepConnectionInstance hwvtepConnectionInstance) {
397         txInvoker.invoke(new HwvtepGlobalRemoveCommand(hwvtepConnectionInstance, null, null));
398         putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(), hwvtepConnectionInstance);
399         hwvtepConnectionInstance.setHasDeviceOwnership(true);
400         hwvtepConnectionInstance.registerCallbacks();
401     }
402
403     private static Global getHwvtepGlobalTableEntry(final HwvtepConnectionInstance connectionInstance) {
404         final TypedDatabaseSchema dbSchema;
405         try {
406             dbSchema = connectionInstance.getSchema(HwvtepSchemaConstants.HARDWARE_VTEP).get();
407         } catch (InterruptedException | ExecutionException e) {
408             LOG.warn("Not able to fetch schema for database {} from device {}",
409                     HwvtepSchemaConstants.HARDWARE_VTEP, connectionInstance.getConnectionInfo(), e);
410             return null;
411         }
412
413         GenericTableSchema hwvtepSchema = dbSchema.getTableSchema(Global.class);
414         Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
415         selectOperation.setColumns(new ArrayList<>(hwvtepSchema.getColumns()));
416
417         ArrayList<Operation> operations = new ArrayList<>(2);
418         operations.add(selectOperation);
419         operations.add(op.comment("Fetching hardware_vtep table rows"));
420
421         final List<OperationResult> results;
422         try {
423             results = connectionInstance.transact(dbSchema, operations).get();
424         } catch (InterruptedException | ExecutionException e) {
425             LOG.warn("Not able to fetch hardware_vtep table row from device {}", connectionInstance.getConnectionInfo(),
426                 e);
427             return null;
428         }
429
430         final Global globalRow;
431         if (results != null) {
432             OperationResult selectResult = results.get(0);
433             globalRow = TyperUtils.getTypedRowWrapper(dbSchema,Global.class,selectResult.getRows().get(0));
434         } else {
435             globalRow = null;
436         }
437         LOG.trace("Fetched global {} from hardware_vtep schema", globalRow);
438         return globalRow;
439     }
440
441     private Entity getEntityFromConnectionInstance(@NonNull final HwvtepConnectionInstance hwvtepConnectionInstance) {
442         InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
443         if (iid == null) {
444             //TODO: Is Global the right one?
445             Global hwvtepGlobalRow = getHwvtepGlobalTableEntry(hwvtepConnectionInstance);
446             iid = HwvtepSouthboundMapper.getInstanceIdentifier(hwvtepGlobalRow);
447             /* Let's set the iid now */
448             hwvtepConnectionInstance.setInstanceIdentifier(iid);
449             LOG.info("InstanceIdentifier {} generated for device "
450                     + "connection {}",iid, hwvtepConnectionInstance.getConnectionInfo());
451             controllerTxHistory.putIfAbsent(iid,
452                     new TransactionHistory(TRANSACTION_HISTORY_CAPACITY, TRANSACTION_HISTORY_WATERMARK));
453             deviceUpdateHistory.putIfAbsent(iid,
454                     new TransactionHistory(TRANSACTION_HISTORY_CAPACITY, TRANSACTION_HISTORY_WATERMARK));
455             TransactionHistory controllerLog = controllerTxHistory.get(iid);
456             TransactionHistory deviceLog = deviceUpdateHistory.get(iid);
457             int port = hwvtepConnectionInstance.getOvsdbClient().getConnectionInfo().getRemotePort();
458             deviceLog.addToHistory(TransactionType.ADD, new ClientConnected(port));
459             hwvtepConnectionInstance.setControllerTxHistory(controllerLog);
460             hwvtepConnectionInstance.setDeviceUpdateHistory(deviceLog);
461         }
462         Entity deviceEntity = new Entity(ENTITY_TYPE, iid);
463         LOG.debug("Entity {} created for device connection {}",
464                 deviceEntity, hwvtepConnectionInstance.getConnectionInfo());
465         return deviceEntity;
466     }
467
468     private void unregisterEntityForOwnership(final HwvtepConnectionInstance hwvtepConnectionInstance) {
469         hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
470         entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
471     }
472
473     public void reconcileConnection(final InstanceIdentifier<Node> iid, final HwvtepGlobalAugmentation hwvtepNode) {
474         this.retryConnection(iid, hwvtepNode,
475                 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
476     }
477
478     public void stopConnectionReconciliationIfActive(final InstanceIdentifier<?> iid,
479             final HwvtepGlobalAugmentation hwvtepNode) {
480         final ReconciliationTask task = new ConnectionReconciliationTask(
481                 reconciliationManager,
482                 this,
483                 iid,
484                 hwvtepNode);
485         reconciliationManager.dequeue(task);
486     }
487
488     private void retryConnection(final InstanceIdentifier<Node> iid, final HwvtepGlobalAugmentation hwvtepNode,
489                                  final ConnectionReconciliationTriggers trigger) {
490         final ReconciliationTask task = new ConnectionReconciliationTask(
491                 reconciliationManager,
492                 this,
493                 iid,
494                 hwvtepNode);
495
496         if (reconciliationManager.isEnqueued(task)) {
497             return;
498         }
499
500         switch (trigger) {
501             case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
502                 reconciliationManager.enqueueForRetry(task);
503                 break;
504             case ON_DISCONNECT: {
505                 ReadOnlyTransaction tx = db.newReadOnlyTransaction();
506                 CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture =
507                         tx.read(LogicalDatastoreType.CONFIGURATION, iid);
508
509                 Futures.addCallback(readNodeFuture, new FutureCallback<Optional<Node>>() {
510                     @Override
511                     public void onSuccess(final Optional<Node> node) {
512                         if (node.isPresent()) {
513                             HwvtepGlobalAugmentation augmentation = node.get()
514                                     .augmentation(HwvtepGlobalAugmentation.class);
515                             if (augmentation == null || augmentation.getConnectionInfo() == null) {
516                                 return;
517                             }
518                             LOG.info(
519                                 "Disconnected/Failed connection {} was controller initiated, attempting reconnection",
520                                 hwvtepNode.getConnectionInfo());
521                             reconciliationManager.enqueue(task);
522
523                         } else {
524                             LOG.debug("Connection {} was switch initiated, no reconciliation is required",
525                                 iid.firstKeyOf(Node.class).getNodeId());
526                         }
527                     }
528
529                     @Override
530                     public void onFailure(final Throwable ex) {
531                         LOG.warn("Read Config/DS for Node failed! {}", iid, ex);
532                     }
533                 }, MoreExecutors.directExecutor());
534                 break;
535             }
536             default:
537                 break;
538         }
539     }
540
541     public void handleOwnershipChanged(final EntityOwnershipChange ownershipChange) {
542         HwvtepConnectionInstance hwvtepConnectionInstance =
543                 getConnectionInstanceFromEntity(ownershipChange.getEntity());
544         LOG.info("handleOwnershipChanged: {} event received for device {}",
545                 ownershipChange, hwvtepConnectionInstance != null ? hwvtepConnectionInstance.getConnectionInfo()
546                         : "THAT'S NOT REGISTERED BY THIS SOUTHBOUND PLUGIN INSTANCE");
547
548         if (hwvtepConnectionInstance == null) {
549             if (ownershipChange.getState().isOwner()) {
550                 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
551             } else {
552                 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
553                 // that instance registered for the device ownership or not. It is to make sure that
554                 // If all the controller instance that was connected to the device are down, so the
555                 // running instance can clear up the operational data store even though it was not
556                 // connected to the device.
557                 LOG.debug("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
558             }
559
560             // If entity has no owner, clean up the operational data store (it's possible because owner controller
561             // might went down abruptly and didn't get a chance to clean up the operational data store.
562             if (!ownershipChange.getState().hasOwner()) {
563                 LOG.debug("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
564                 // If first cleanEntityOperationalData() was called, this call will be no-op.
565                 cleanEntityOperationalData(ownershipChange.getEntity());
566             }
567             return;
568         }
569         //Connection detail need to be cached, irrespective of ownership result.
570         putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(), hwvtepConnectionInstance);
571
572         if (ownershipChange.getState().isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
573             LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
574                     hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
575             return;
576         }
577
578         hwvtepConnectionInstance.setHasDeviceOwnership(ownershipChange.getState().isOwner());
579         // You were not an owner, but now you are
580         if (ownershipChange.getState().isOwner()) {
581             LOG.info("handleOwnershipChanged: *this* southbound plugin instance is owner of device {}",
582                     hwvtepConnectionInstance.getConnectionInfo());
583
584             //*this* instance of southbound plugin is owner of the device,
585             //so register for monitor callbacks
586             afterTakingOwnership(hwvtepConnectionInstance);
587
588         } else {
589             //You were owner of the device, but now you are not. With the current ownership
590             //grant mechanism, this scenario should not occur. Because this scenario will occur
591             //when this controller went down or switch flap the connection, but in both the case
592             //it will go through the re-registration process. We need to implement this condition
593             //when clustering service implement a ownership grant strategy which can revoke the
594             //device ownership for load balancing the devices across the instances.
595             //Once this condition occur, we should unregister the callback.
596             LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}",
597                     hwvtepConnectionInstance.getNodeId().getValue());
598         }
599     }
600
601     private void cleanEntityOperationalData(final Entity entity) {
602         @SuppressWarnings("unchecked")
603         final InstanceIdentifier<Node> nodeIid = (InstanceIdentifier<Node>) entity.getIdentifier();
604         txInvoker.invoke(new HwvtepGlobalRemoveCommand(nodeIid));
605     }
606
607     private HwvtepConnectionInstance getConnectionInstanceFromEntity(final Entity entity) {
608         return entityConnectionMap.get(entity);
609     }
610
611     public Map<InstanceIdentifier<Node>, TransactionHistory> getControllerTxHistory() {
612         return controllerTxHistory;
613     }
614
615     public Map<InstanceIdentifier<Node>, TransactionHistory> getDeviceUpdateHistory() {
616         return deviceUpdateHistory;
617     }
618
619     private static class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
620         private final HwvtepConnectionManager hcm;
621         private final EntityOwnershipListenerRegistration listenerRegistration;
622
623         HwvtepDeviceEntityOwnershipListener(final HwvtepConnectionManager hcm,
624                 final EntityOwnershipService entityOwnershipService) {
625             this.hcm = hcm;
626             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
627         }
628
629         public void close() {
630             listenerRegistration.close();
631         }
632
633         @Override
634         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
635             hcm.handleOwnershipChanged(ownershipChange);
636         }
637     }
638
639     private enum ConnectionReconciliationTriggers {
640         /*
641         Reconciliation trigger for scenario where controller's attempt
642         to connect to switch fails on config data store notification
643         */
644         ON_CONTROLLER_INITIATED_CONNECTION_FAILURE,
645
646         /*
647         Reconciliation trigger for the scenario where controller
648         initiated connection disconnects.
649         */
650         ON_DISCONNECT
651     }
652
653     public Map<InstanceIdentifier<Node>, HwvtepConnectionInstance> getAllConnectedInstances() {
654         return Collections.unmodifiableMap(nodeIidVsConnectionInstance);
655     }
656 }