Merge "BUG-5006: rework SouthboundProviderTest, clean up"
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / OvsdbConnectionManager.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.ovsdb.southbound;
9
10 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
11
12 import java.net.InetAddress;
13 import java.net.UnknownHostException;
14 import java.util.ArrayList;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.concurrent.ConcurrentHashMap;
18 import java.util.concurrent.ExecutionException;
19
20 import javax.annotation.Nonnull;
21
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
24 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
25 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
26 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
27 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
28 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
29 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
30 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
31 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
32 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
33 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
34 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
35 import org.opendaylight.ovsdb.lib.OvsdbClient;
36 import org.opendaylight.ovsdb.lib.OvsdbConnection;
37 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
38 import org.opendaylight.ovsdb.lib.operations.Operation;
39 import org.opendaylight.ovsdb.lib.operations.OperationResult;
40 import org.opendaylight.ovsdb.lib.operations.Select;
41 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
42 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
43 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
44 import org.opendaylight.ovsdb.schema.openvswitch.OpenVSwitch;
45 import org.opendaylight.ovsdb.southbound.transactions.md.OvsdbNodeRemoveCommand;
46 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionCommand;
47 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
53 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
54 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import com.google.common.base.Optional;
60 import com.google.common.base.Preconditions;
61 import com.google.common.util.concurrent.CheckedFuture;
62
63 public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoCloseable {
64     private Map<ConnectionInfo, OvsdbConnectionInstance> clients =
65             new ConcurrentHashMap<>();
66     private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionManager.class);
67     private static final String ENTITY_TYPE = "ovsdb";
68
69     private DataBroker db;
70     private TransactionInvoker txInvoker;
71     private Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
72             new ConcurrentHashMap<>();
73     private Map<Entity, OvsdbConnectionInstance> entityConnectionMap =
74             new ConcurrentHashMap<>();
75     private EntityOwnershipService entityOwnershipService;
76     private OvsdbDeviceEntityOwnershipListener ovsdbDeviceEntityOwnershipListener;
77     private OvsdbConnection ovsdbConnection;
78
79     public OvsdbConnectionManager(DataBroker db,TransactionInvoker txInvoker,
80                                   EntityOwnershipService entityOwnershipService,
81                                   OvsdbConnection ovsdbConnection) {
82         this.db = db;
83         this.txInvoker = txInvoker;
84         this.entityOwnershipService = entityOwnershipService;
85         this.ovsdbDeviceEntityOwnershipListener = new OvsdbDeviceEntityOwnershipListener(this, entityOwnershipService);
86         this.ovsdbConnection = ovsdbConnection;
87     }
88
89     @Override
90     public void connected(@Nonnull final OvsdbClient externalClient) {
91         LOG.info("Library connected {} from {}:{} to {}:{}",
92                 externalClient.getConnectionInfo().getType(),
93                 externalClient.getConnectionInfo().getRemoteAddress(),
94                 externalClient.getConnectionInfo().getRemotePort(),
95                 externalClient.getConnectionInfo().getLocalAddress(),
96                 externalClient.getConnectionInfo().getLocalPort());
97         if(externalClient.getSchema(SouthboundConstants.OPEN_V_SWITCH) != null) {
98             OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
99             // Register Cluster Ownership for ConnectionInfo
100             registerEntityForOwnership(client);
101         }
102     }
103
104     public OvsdbConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
105         LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
106                 externalClient.getConnectionInfo().getRemotePort());
107         ConnectionInfo key = SouthboundMapper.createConnectionInfo(externalClient);
108         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
109
110         // Check if existing ovsdbConnectionInstance for the OvsdbClient present.
111         // In such cases, we will see if the ovsdbConnectionInstance has same externalClient.
112         if (ovsdbConnectionInstance != null) {
113             if (ovsdbConnectionInstance.hasOvsdbClient(externalClient)) {
114                 LOG.warn("OVSDB Connection Instance {} already exists for client {}", key, externalClient);
115                 return ovsdbConnectionInstance;
116             }
117             LOG.warn("OVSDB Connection Instance {} being replaced with client {}", key, externalClient);
118
119             // Unregister Cluster Ownership for ConnectionInfo
120             // Because the ovsdbConnectionInstance is about to be completely replaced!
121             unregisterEntityForOwnership(ovsdbConnectionInstance);
122
123             ovsdbConnectionInstance.disconnect();
124
125             removeConnectionInstance(key);
126         }
127
128         ovsdbConnectionInstance = new OvsdbConnectionInstance(key, externalClient, txInvoker,
129                 getInstanceIdentifier(key));
130         ovsdbConnectionInstance.createTransactInvokers();
131         return ovsdbConnectionInstance;
132     }
133
134     @Override
135     public void disconnected(OvsdbClient client) {
136         LOG.info("Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
137                 client.getConnectionInfo().getType(),
138                 client.getConnectionInfo().getRemoteAddress(),
139                 client.getConnectionInfo().getRemotePort(),
140                 client.getConnectionInfo().getLocalAddress(),
141                 client.getConnectionInfo().getLocalPort());
142         ConnectionInfo key = SouthboundMapper.createConnectionInfo(client);
143         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
144         if (ovsdbConnectionInstance != null) {
145             // Unregister Entity ownership as soon as possible ,so this instance should
146             // not be used as a candidate in Entity election (given that this instance is
147             // about to disconnect as well), if current owner get disconnected from
148             // OVSDB device.
149             unregisterEntityForOwnership(ovsdbConnectionInstance);
150
151             txInvoker.invoke(new OvsdbNodeRemoveCommand(ovsdbConnectionInstance, null, null));
152
153             removeConnectionInstance(key);
154         } else {
155             LOG.warn("disconnected : Connection instance not found for OVSDB Node {} ", key);
156         }
157         LOG.trace("OvsdbConnectionManager: exit disconnected client: {}", client);
158     }
159
160     public OvsdbClient connect(InstanceIdentifier<Node> iid,
161             OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
162         LOG.info("Connecting to {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
163
164         // TODO handle case where we already have a connection
165         // TODO use transaction chains to handle ordering issues between disconnected
166         // TODO and connected when writing to the operational store
167         InetAddress ip = SouthboundMapper.createInetAddress(ovsdbNode.getConnectionInfo().getRemoteIp());
168         OvsdbClient client = ovsdbConnection.connect(ip,
169                 ovsdbNode.getConnectionInfo().getRemotePort().getValue());
170         // For connections from the controller to the ovs instance, the library doesn't call
171         // this method for us
172         if (client != null) {
173             putInstanceIdentifier(ovsdbNode.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
174             OvsdbConnectionInstance ovsdbConnectionInstance = connectedButCallBacksNotRegistered(client);
175             ovsdbConnectionInstance.setOvsdbNodeAugmentation(ovsdbNode);
176
177             // Register Cluster Ownership for ConnectionInfo
178             registerEntityForOwnership(ovsdbConnectionInstance);
179         } else {
180             LOG.warn("Failed to connect to OVSDB Node {}", ovsdbNode.getConnectionInfo());
181         }
182         return client;
183     }
184
185     public void disconnect(OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
186         LOG.info("Disconnecting from {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
187         OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
188         if (client != null) {
189             // Unregister Cluster Onwership for ConnectionInfo
190             unregisterEntityForOwnership(client);
191
192             client.disconnect();
193
194             removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
195         } else {
196             LOG.debug("disconnect : connection instance not found for {}",ovsdbNode.getConnectionInfo());
197         }
198     }
199
200 /*    public void init(ConnectionInfo key) {
201         OvsdbConnectionInstance client = getConnectionInstance(key);
202
203         // TODO (FF): make sure that this cluster instance is the 'entity owner' fo the given OvsdbConnectionInstance ?
204
205         if (client != null) {
206
207              *  Note: registerCallbacks() is idemPotent... so if you call it repeatedly all is safe,
208              *  it only registersCallbacks on the *first* call.
209
210             client.registerCallbacks();
211         }
212     }
213 */
214     @Override
215     public void close() {
216         if (ovsdbDeviceEntityOwnershipListener != null) {
217             ovsdbDeviceEntityOwnershipListener.close();
218         }
219
220         for (OvsdbClient client: clients.values()) {
221             client.disconnect();
222         }
223     }
224
225     private void putConnectionInstance(ConnectionInfo key,OvsdbConnectionInstance instance) {
226         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
227         clients.put(connectionInfo, instance);
228     }
229
230     private void removeConnectionInstance(ConnectionInfo key) {
231         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
232         clients.remove(connectionInfo);
233     }
234
235     private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
236         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
237         instanceIdentifiers.put(connectionInfo, iid);
238     }
239
240     private void removeInstanceIdentifier(ConnectionInfo key) {
241         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
242         instanceIdentifiers.remove(connectionInfo);
243     }
244
245     public OvsdbConnectionInstance getConnectionInstance(ConnectionInfo key) {
246         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
247         return clients.get(connectionInfo);
248     }
249
250     public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
251         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
252         return instanceIdentifiers.get(connectionInfo);
253     }
254
255     public OvsdbConnectionInstance getConnectionInstance(OvsdbBridgeAttributes mn) {
256         Optional<OvsdbNodeAugmentation> optional = SouthboundUtil.getManagingNode(db, mn);
257         if (optional.isPresent()) {
258             return getConnectionInstance(optional.get().getConnectionInfo());
259         } else {
260             return null;
261         }
262     }
263
264     public OvsdbConnectionInstance getConnectionInstance(Node node) {
265         Preconditions.checkNotNull(node);
266         OvsdbNodeAugmentation ovsdbNode = node.getAugmentation(OvsdbNodeAugmentation.class);
267         OvsdbBridgeAugmentation ovsdbManagedNode = node.getAugmentation(OvsdbBridgeAugmentation.class);
268         if (ovsdbNode != null) {
269             return getConnectionInstance(ovsdbNode.getConnectionInfo());
270         } else if (ovsdbManagedNode != null) {
271             return getConnectionInstance(ovsdbManagedNode);
272         } else {
273             LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
274             return null;
275         }
276     }
277
278     public OvsdbConnectionInstance getConnectionInstance(InstanceIdentifier<Node> nodePath) {
279         try {
280             ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
281             CheckedFuture<Optional<Node>, ReadFailedException> nodeFuture = transaction.read(
282                     LogicalDatastoreType.OPERATIONAL, nodePath);
283             transaction.close();
284             Optional<Node> optional = nodeFuture.get();
285             if (optional != null && optional.isPresent() && optional.get() != null) {
286                 return this.getConnectionInstance(optional.get());
287             } else {
288                 LOG.warn("Found non-topological node {} on path {}",optional);
289                 return null;
290             }
291         } catch (Exception e) {
292             LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
293             return null;
294         }
295     }
296
297     public OvsdbClient getClient(ConnectionInfo connectionInfo) {
298         return getConnectionInstance(connectionInfo);
299     }
300
301     public OvsdbClient getClient(OvsdbBridgeAttributes mn) {
302         return getConnectionInstance(mn);
303     }
304
305     public OvsdbClient getClient(Node node) {
306         return getConnectionInstance(node);
307     }
308
309     public Boolean getHasDeviceOwnership(ConnectionInfo connectionInfo) {
310         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(connectionInfo);
311         if (ovsdbConnectionInstance == null) {
312             return Boolean.FALSE;
313         }
314         return ovsdbConnectionInstance.getHasDeviceOwnership();
315     }
316
317     private void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
318         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
319         LOG.debug("handleOwnershipChanged: {} event received for device {}",
320                 ownershipChange, ovsdbConnectionInstance != null ? ovsdbConnectionInstance.getConnectionInfo()
321                         : "that's currently NOT registered by *this* southbound plugin instance");
322
323         if (ovsdbConnectionInstance == null) {
324             if (ownershipChange.isOwner()) {
325                 LOG.warn("handleOwnershipChanged: *this* instance is elected as an owner of the device {} but it "
326                         + "is NOT registered for ownership", ownershipChange.getEntity());
327             } else {
328                 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
329                 // that instance registered for the device ownership or not. It is to make sure that
330                 // If all the controller instance that was connected to the device are down, so the
331                 // running instance can clear up the operational data store even though it was not
332                 // connected to the device.
333                 LOG.debug("handleOwnershipChanged: No connection instance found for {}", ownershipChange.getEntity());
334             }
335
336             // If entity has no owner, clean up the operational data store (it's possible because owner controller
337             // might went down abruptly and didn't get a chance to clean up the operational data store.
338             if (!ownershipChange.hasOwner()) {
339                 LOG.info("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
340                 cleanEntityOperationalData(ownershipChange.getEntity());
341             }
342             return;
343         }
344         //Connection detail need to be cached, irrespective of ownership result.
345         putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
346
347         if (ownershipChange.isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
348             LOG.info("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
349                     ovsdbConnectionInstance.getConnectionInfo(), ovsdbConnectionInstance.getHasDeviceOwnership()
350                             ? SouthboundConstants.OWNERSHIPSTATES.OWNER.getState()
351                             : SouthboundConstants.OWNERSHIPSTATES.NONOWNER.getState());
352             return;
353         }
354
355         ovsdbConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
356         // You were not an owner, but now you are
357         if (ownershipChange.isOwner()) {
358             LOG.info("handleOwnershipChanged: *this* southbound plugin instance is an OWNER of the device {}",
359                     ovsdbConnectionInstance.getConnectionInfo());
360
361             //*this* instance of southbound plugin is owner of the device,
362             //so register for monitor callbacks
363             ovsdbConnectionInstance.registerCallbacks();
364
365         } else {
366             //You were owner of the device, but now you are not. With the current ownership
367             //grant mechanism, this scenario should not occur. Because this scenario will occur
368             //when this controller went down or switch flap the connection, but in both the case
369             //it will go through the re-registration process. We need to implement this condition
370             //when clustering service implement a ownership grant strategy which can revoke the
371             //device ownership for load balancing the devices across the instances.
372             //Once this condition occur, we should unregister the callback.
373             LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}."
374                     + "This should NOT happen.",
375                     ovsdbConnectionInstance.getNodeId().getValue());
376         }
377     }
378
379     private void cleanEntityOperationalData(Entity entity) {
380
381         //Do explicit cleanup rather than using OvsdbNodeRemoveCommand, because there
382         // are chances that other controller instance went down abruptly and it does
383         // not clear manager entry, which OvsdbNodeRemoveCommand look for before cleanup.
384
385         @SuppressWarnings("unchecked") final InstanceIdentifier<Node> nodeIid =
386                 (InstanceIdentifier<Node>) SouthboundUtil
387                         .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
388
389         txInvoker.invoke(new TransactionCommand() {
390             @Override
391             public void execute(ReadWriteTransaction transaction) {
392                 Optional<Node> ovsdbNodeOpt = SouthboundUtil.readNode(transaction, nodeIid);
393                 if (ovsdbNodeOpt.isPresent()) {
394                     Node ovsdbNode = ovsdbNodeOpt.get();
395                     OvsdbNodeAugmentation nodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
396                     if (nodeAugmentation != null) {
397                         if (nodeAugmentation.getManagedNodeEntry() != null) {
398                             for (ManagedNodeEntry managedNode : nodeAugmentation.getManagedNodeEntry()) {
399                                 transaction.delete(
400                                         LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
401                             }
402                         } else {
403                             LOG.debug("{} had no managed nodes", ovsdbNode.getNodeId().getValue());
404                         }
405                     }
406                     transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
407                 }
408             }
409         });
410
411     }
412
413     private OpenVSwitch getOpenVswitchTableEntry(OvsdbConnectionInstance connectionInstance) {
414         DatabaseSchema dbSchema = null;
415         OpenVSwitch openVSwitchRow = null;
416         try {
417             dbSchema = connectionInstance.getSchema(OvsdbSchemaContants.databaseName).get();
418         } catch (InterruptedException | ExecutionException e) {
419             LOG.warn("Not able to fetch schema for database {} from device {}",
420                     OvsdbSchemaContants.databaseName,connectionInstance.getConnectionInfo(),e);
421         }
422         if (dbSchema != null) {
423             GenericTableSchema openVSwitchSchema = TyperUtils.getTableSchema(dbSchema, OpenVSwitch.class);
424
425             List<String> openVSwitchTableColumn = new ArrayList<>();
426             openVSwitchTableColumn.addAll(openVSwitchSchema.getColumns());
427             Select<GenericTableSchema> selectOperation = op.select(openVSwitchSchema);
428             selectOperation.setColumns(openVSwitchTableColumn);
429
430             List<Operation> operations = new ArrayList<>();
431             operations.add(selectOperation);
432             operations.add(op.comment("Fetching Open_VSwitch table rows"));
433             try {
434                 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
435                 if (results != null ) {
436                     OperationResult selectResult = results.get(0);
437                     openVSwitchRow = TyperUtils.getTypedRowWrapper(
438                             dbSchema,OpenVSwitch.class,selectResult.getRows().get(0));
439
440                 }
441             } catch (InterruptedException | ExecutionException e) {
442                 LOG.warn("Not able to fetch OpenVswitch table row from device {}",
443                         connectionInstance.getConnectionInfo(),e);
444             }
445         }
446         return openVSwitchRow;
447     }
448     private Entity getEntityFromConnectionInstance(@Nonnull OvsdbConnectionInstance ovsdbConnectionInstance) {
449         InstanceIdentifier<Node> iid = ovsdbConnectionInstance.getInstanceIdentifier();
450         if ( iid == null ) {
451             /* Switch initiated connection won't have iid, till it gets OpenVSwitch
452              * table update but update callback is always registered after ownership
453              * is granted. So we are explicitly fetch the row here to get the iid.
454              */
455             OpenVSwitch openvswitchRow = getOpenVswitchTableEntry(ovsdbConnectionInstance);
456             iid = SouthboundMapper.getInstanceIdentifier(openvswitchRow);
457             LOG.info("InstanceIdentifier {} generated for device "
458                     + "connection {}",iid,ovsdbConnectionInstance.getConnectionInfo());
459             ovsdbConnectionInstance.setInstanceIdentifier(iid);
460         }
461         YangInstanceIdentifier entityId = SouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
462         Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
463         LOG.debug("Entity {} created for device connection {}",
464                 deviceEntity, ovsdbConnectionInstance.getConnectionInfo());
465         return deviceEntity;
466     }
467
468     private OvsdbConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
469         return entityConnectionMap.get(entity);
470     }
471
472     private void registerEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
473
474         Entity candidateEntity = getEntityFromConnectionInstance(ovsdbConnectionInstance);
475         entityConnectionMap.put(candidateEntity, ovsdbConnectionInstance);
476         ovsdbConnectionInstance.setConnectedEntity(candidateEntity);
477         try {
478             EntityOwnershipCandidateRegistration registration =
479                     entityOwnershipService.registerCandidate(candidateEntity);
480             ovsdbConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
481             LOG.info("OVSDB entity {} is registered for ownership.", candidateEntity);
482
483             //If entity already has owner, it won't get notification from EntityOwnershipService
484             //so cache the connection instances.
485             Optional<EntityOwnershipState> ownershipStateOpt =
486                     entityOwnershipService.getOwnershipState(candidateEntity);
487             if (ownershipStateOpt.isPresent()) {
488                 EntityOwnershipState ownershipState = ownershipStateOpt.get();
489                 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
490                     LOG.info("OVSDB entity {} is already owned by other southbound plugin "
491                                     + "instance, so *this* instance is NOT an OWNER of the device",
492                             ovsdbConnectionInstance.getConnectionInfo());
493                     putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
494                 }
495             }
496         } catch (CandidateAlreadyRegisteredException e) {
497             LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
498         }
499
500     }
501
502     private void unregisterEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
503         ovsdbConnectionInstance.closeDeviceOwnershipCandidateRegistration();
504         entityConnectionMap.remove(ovsdbConnectionInstance.getConnectedEntity());
505     }
506
507     private class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
508         private OvsdbConnectionManager cm;
509         private EntityOwnershipListenerRegistration listenerRegistration;
510
511         OvsdbDeviceEntityOwnershipListener(OvsdbConnectionManager cm, EntityOwnershipService entityOwnershipService) {
512             this.cm = cm;
513             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
514         }
515         public void close() {
516             listenerRegistration.close();
517         }
518         @Override
519         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
520             cm.handleOwnershipChanged(ownershipChange);
521         }
522     }
523 }