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