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