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