2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.ovsdb.southbound;
10 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
18 import java.net.ConnectException;
19 import java.net.InetAddress;
20 import java.net.UnknownHostException;
21 import java.util.ArrayList;
22 import java.util.List;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.TimeUnit;
27 import java.util.concurrent.TimeoutException;
28 import javax.annotation.Nonnull;
29 import javax.annotation.Nullable;
30 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
31 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
32 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
33 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
34 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
35 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
36 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
37 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
38 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
39 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
40 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
41 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
42 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
43 import org.opendaylight.ovsdb.lib.OvsdbClient;
44 import org.opendaylight.ovsdb.lib.OvsdbConnection;
45 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
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.openvswitch.OpenVSwitch;
53 import org.opendaylight.ovsdb.southbound.reconciliation.ReconciliationManager;
54 import org.opendaylight.ovsdb.southbound.reconciliation.ReconciliationTask;
55 import org.opendaylight.ovsdb.southbound.reconciliation.configuration.BridgeConfigReconciliationTask;
56 import org.opendaylight.ovsdb.southbound.reconciliation.connection.ConnectionReconciliationTask;
57 import org.opendaylight.ovsdb.southbound.transactions.md.OvsdbNodeRemoveCommand;
58 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionCommand;
59 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
65 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
66 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
71 public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoCloseable {
72 private Map<ConnectionInfo, OvsdbConnectionInstance> clients =
73 new ConcurrentHashMap<>();
74 private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionManager.class);
75 private static final String ENTITY_TYPE = "ovsdb";
76 private static final int DB_FETCH_TIMEOUT = 1000;
78 private DataBroker db;
79 private TransactionInvoker txInvoker;
80 private Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
81 new ConcurrentHashMap<>();
82 private Map<Entity, OvsdbConnectionInstance> entityConnectionMap =
83 new ConcurrentHashMap<>();
84 private EntityOwnershipService entityOwnershipService;
85 private OvsdbDeviceEntityOwnershipListener ovsdbDeviceEntityOwnershipListener;
86 private OvsdbConnection ovsdbConnection;
87 private final ReconciliationManager reconciliationManager;
89 public OvsdbConnectionManager(DataBroker db,TransactionInvoker txInvoker,
90 EntityOwnershipService entityOwnershipService,
91 OvsdbConnection ovsdbConnection) {
93 this.txInvoker = txInvoker;
94 this.entityOwnershipService = entityOwnershipService;
95 this.ovsdbDeviceEntityOwnershipListener = new OvsdbDeviceEntityOwnershipListener(this, entityOwnershipService);
96 this.ovsdbConnection = ovsdbConnection;
97 this.reconciliationManager = new ReconciliationManager(db);
101 public void connected(@Nonnull final OvsdbClient externalClient) {
102 LOG.info("Library connected {} from {}:{} to {}:{}",
103 externalClient.getConnectionInfo().getType(),
104 externalClient.getConnectionInfo().getRemoteAddress(),
105 externalClient.getConnectionInfo().getRemotePort(),
106 externalClient.getConnectionInfo().getLocalAddress(),
107 externalClient.getConnectionInfo().getLocalPort());
108 List<String> databases = new ArrayList<>();
110 databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
111 if (databases.contains(SouthboundConstants.OPEN_V_SWITCH)) {
112 OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
113 // Register Cluster Ownership for ConnectionInfo
114 registerEntityForOwnership(client);
116 } catch (InterruptedException | ExecutionException | TimeoutException e) {
117 LOG.warn("Unable to fetch Database list from device {}. Disconnecting from the device.",
118 externalClient.getConnectionInfo().getRemoteAddress(), e);
119 externalClient.disconnect();
124 public OvsdbConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
125 LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
126 externalClient.getConnectionInfo().getRemotePort());
127 ConnectionInfo key = SouthboundMapper.createConnectionInfo(externalClient);
128 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
130 // Check if existing ovsdbConnectionInstance for the OvsdbClient present.
131 // In such cases, we will see if the ovsdbConnectionInstance has same externalClient.
132 if (ovsdbConnectionInstance != null) {
133 if (ovsdbConnectionInstance.hasOvsdbClient(externalClient)) {
134 LOG.warn("OVSDB Connection Instance {} already exists for client {}", key, externalClient);
135 return ovsdbConnectionInstance;
137 LOG.warn("OVSDB Connection Instance {} being replaced with client {}", key, externalClient);
139 // Unregister Cluster Ownership for ConnectionInfo
140 // Because the ovsdbConnectionInstance is about to be completely replaced!
141 unregisterEntityForOwnership(ovsdbConnectionInstance);
143 ovsdbConnectionInstance.disconnect();
145 removeConnectionInstance(key);
147 stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
150 ovsdbConnectionInstance = new OvsdbConnectionInstance(key, externalClient, txInvoker,
151 getInstanceIdentifier(key));
152 ovsdbConnectionInstance.createTransactInvokers();
153 return ovsdbConnectionInstance;
157 public void disconnected(OvsdbClient client) {
158 LOG.info("Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
159 client.getConnectionInfo().getType(),
160 client.getConnectionInfo().getRemoteAddress(),
161 client.getConnectionInfo().getRemotePort(),
162 client.getConnectionInfo().getLocalAddress(),
163 client.getConnectionInfo().getLocalPort());
164 ConnectionInfo key = SouthboundMapper.createConnectionInfo(client);
165 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
166 if (ovsdbConnectionInstance != null) {
167 // Unregister Entity ownership as soon as possible ,so this instance should
168 // not be used as a candidate in Entity election (given that this instance is
169 // about to disconnect as well), if current owner get disconnected from
171 unregisterEntityForOwnership(ovsdbConnectionInstance);
173 txInvoker.invoke(new OvsdbNodeRemoveCommand(ovsdbConnectionInstance, null, null));
175 removeConnectionInstance(key);
177 //Controller initiated connection can be terminated from switch side.
178 //So cleanup the instance identifier cache.
179 removeInstanceIdentifier(key);
180 stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
181 retryConnection(ovsdbConnectionInstance.getInstanceIdentifier(),
182 ovsdbConnectionInstance.getOvsdbNodeAugmentation(),
183 ConnectionReconciliationTriggers.ON_DISCONNECT);
185 LOG.warn("disconnected : Connection instance not found for OVSDB Node {} ", key);
187 LOG.trace("OvsdbConnectionManager: exit disconnected client: {}", client);
190 public OvsdbClient connect(InstanceIdentifier<Node> iid,
191 OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException, ConnectException {
192 LOG.info("Connecting to {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
194 // TODO handle case where we already have a connection
195 // TODO use transaction chains to handle ordering issues between disconnected
196 // TODO and connected when writing to the operational store
197 InetAddress ip = SouthboundMapper.createInetAddress(ovsdbNode.getConnectionInfo().getRemoteIp());
198 OvsdbClient client = ovsdbConnection.connect(ip,
199 ovsdbNode.getConnectionInfo().getRemotePort().getValue());
200 // For connections from the controller to the ovs instance, the library doesn't call
201 // this method for us
202 if (client != null) {
203 putInstanceIdentifier(ovsdbNode.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
204 OvsdbConnectionInstance ovsdbConnectionInstance = connectedButCallBacksNotRegistered(client);
205 ovsdbConnectionInstance.setOvsdbNodeAugmentation(ovsdbNode);
207 // Register Cluster Ownership for ConnectionInfo
208 registerEntityForOwnership(ovsdbConnectionInstance);
210 LOG.warn("Failed to connect to OVSDB Node {}", ovsdbNode.getConnectionInfo());
215 public void disconnect(OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
216 LOG.info("Disconnecting from {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
217 OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
218 if (client != null) {
219 // Unregister Cluster Onwership for ConnectionInfo
220 unregisterEntityForOwnership(client);
224 removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
226 stopBridgeConfigReconciliationIfActive(client.getInstanceIdentifier());
228 LOG.debug("disconnect : connection instance not found for {}",ovsdbNode.getConnectionInfo());
232 /* public void init(ConnectionInfo key) {
233 OvsdbConnectionInstance client = getConnectionInstance(key);
235 // TODO (FF): make sure that this cluster instance is the 'entity owner' fo the given OvsdbConnectionInstance ?
237 if (client != null) {
239 * Note: registerCallbacks() is idemPotent... so if you call it repeatedly all is safe,
240 * it only registersCallbacks on the *first* call.
242 client.registerCallbacks();
247 public void close() {
248 if (ovsdbDeviceEntityOwnershipListener != null) {
249 ovsdbDeviceEntityOwnershipListener.close();
252 for (OvsdbConnectionInstance client: clients.values()) {
257 private void putConnectionInstance(ConnectionInfo key,OvsdbConnectionInstance instance) {
258 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
259 clients.put(connectionInfo, instance);
262 private void removeConnectionInstance(ConnectionInfo key) {
263 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
264 clients.remove(connectionInfo);
267 private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
268 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
269 instanceIdentifiers.put(connectionInfo, iid);
272 private void removeInstanceIdentifier(ConnectionInfo key) {
273 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
274 instanceIdentifiers.remove(connectionInfo);
277 public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
278 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
279 return instanceIdentifiers.get(connectionInfo);
282 public OvsdbConnectionInstance getConnectionInstance(ConnectionInfo key) {
283 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
284 return clients.get(connectionInfo);
287 public OvsdbConnectionInstance getConnectionInstance(OvsdbBridgeAttributes mn) {
288 Optional<OvsdbNodeAugmentation> optional = SouthboundUtil.getManagingNode(db, mn);
289 if (optional.isPresent()) {
290 return getConnectionInstance(optional.get().getConnectionInfo());
296 public OvsdbConnectionInstance getConnectionInstance(Node node) {
297 Preconditions.checkNotNull(node);
298 OvsdbNodeAugmentation ovsdbNode = node.getAugmentation(OvsdbNodeAugmentation.class);
299 OvsdbBridgeAugmentation ovsdbManagedNode = node.getAugmentation(OvsdbBridgeAugmentation.class);
300 if (ovsdbNode != null) {
301 return getConnectionInstance(ovsdbNode.getConnectionInfo());
302 } else if (ovsdbManagedNode != null) {
303 return getConnectionInstance(ovsdbManagedNode);
305 LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
310 public OvsdbConnectionInstance getConnectionInstance(InstanceIdentifier<Node> nodePath) {
312 ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
313 CheckedFuture<Optional<Node>, ReadFailedException> nodeFuture = transaction.read(
314 LogicalDatastoreType.OPERATIONAL, nodePath);
316 Optional<Node> optional = nodeFuture.get();
317 if (optional != null && optional.isPresent() && optional.get() != null) {
318 return this.getConnectionInstance(optional.get());
320 LOG.warn("Found non-topological node {} on path {}",optional);
323 } catch (InterruptedException | ExecutionException e) {
324 LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
329 public OvsdbClient getClient(ConnectionInfo connectionInfo) {
330 return getConnectionInstance(connectionInfo).getOvsdbClient();
333 public OvsdbClient getClient(OvsdbBridgeAttributes mn) {
334 return getConnectionInstance(mn).getOvsdbClient();
337 public OvsdbClient getClient(Node node) {
338 return getConnectionInstance(node).getOvsdbClient();
341 public Boolean getHasDeviceOwnership(ConnectionInfo connectionInfo) {
342 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(connectionInfo);
343 if (ovsdbConnectionInstance == null) {
344 return Boolean.FALSE;
346 return ovsdbConnectionInstance.getHasDeviceOwnership();
349 public void reconcileConnection(InstanceIdentifier<Node> iid, OvsdbNodeAugmentation ovsdbNode) {
350 this.retryConnection(iid, ovsdbNode,
351 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
355 public void stopConnectionReconciliationIfActive(InstanceIdentifier<?> iid, OvsdbNodeAugmentation ovsdbNode) {
356 final ReconciliationTask task = new ConnectionReconciliationTask(
357 reconciliationManager,
361 reconciliationManager.dequeue(task);
364 public void stopBridgeConfigReconciliationIfActive(InstanceIdentifier<?> iid) {
365 final ReconciliationTask task = new BridgeConfigReconciliationTask(
366 reconciliationManager,
370 reconciliationManager.dequeue(task);
371 reconciliationManager.cancelTerminationPointReconciliation();
374 private void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
375 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
376 LOG.debug("handleOwnershipChanged: {} event received for device {}",
377 ownershipChange, ovsdbConnectionInstance != null ? ovsdbConnectionInstance.getConnectionInfo()
378 : "that's currently NOT registered by *this* southbound plugin instance");
380 if (ovsdbConnectionInstance == null) {
381 if (ownershipChange.isOwner()) {
382 LOG.warn("handleOwnershipChanged: *this* instance is elected as an owner of the device {} but it "
383 + "is NOT registered for ownership", ownershipChange.getEntity());
385 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
386 // that instance registered for the device ownership or not. It is to make sure that
387 // If all the controller instance that was connected to the device are down, so the
388 // running instance can clear up the operational data store even though it was not
389 // connected to the device.
390 LOG.debug("handleOwnershipChanged: No connection instance found for {}", ownershipChange.getEntity());
393 // If entity has no owner, clean up the operational data store (it's possible because owner controller
394 // might went down abruptly and didn't get a chance to clean up the operational data store.
395 if (!ownershipChange.hasOwner()) {
396 LOG.info("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
397 cleanEntityOperationalData(ownershipChange.getEntity());
401 //Connection detail need to be cached, irrespective of ownership result.
402 putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
404 if (ownershipChange.isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
405 LOG.info("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
406 ovsdbConnectionInstance.getConnectionInfo(), ovsdbConnectionInstance.getHasDeviceOwnership()
407 ? SouthboundConstants.OwnershipStates.OWNER.getState()
408 : SouthboundConstants.OwnershipStates.NONOWNER.getState());
412 ovsdbConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
413 // You were not an owner, but now you are
414 if (ownershipChange.isOwner()) {
415 LOG.info("handleOwnershipChanged: *this* southbound plugin instance is an OWNER of the device {}",
416 ovsdbConnectionInstance.getConnectionInfo());
418 //*this* instance of southbound plugin is owner of the device,
419 //so register for monitor callbacks
420 ovsdbConnectionInstance.registerCallbacks();
422 reconcileBridgeConfigurations(ovsdbConnectionInstance);
424 //You were owner of the device, but now you are not. With the current ownership
425 //grant mechanism, this scenario should not occur. Because this scenario will occur
426 //when this controller went down or switch flap the connection, but in both the case
427 //it will go through the re-registration process. We need to implement this condition
428 //when clustering service implement a ownership grant strategy which can revoke the
429 //device ownership for load balancing the devices across the instances.
430 //Once this condition occur, we should unregister the callback.
431 LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}."
432 + "This should NOT happen.",
433 ovsdbConnectionInstance.getNodeId().getValue());
437 private void cleanEntityOperationalData(Entity entity) {
439 //Do explicit cleanup rather than using OvsdbNodeRemoveCommand, because there
440 // are chances that other controller instance went down abruptly and it does
441 // not clear manager entry, which OvsdbNodeRemoveCommand look for before cleanup.
443 @SuppressWarnings("unchecked") final InstanceIdentifier<Node> nodeIid =
444 (InstanceIdentifier<Node>) SouthboundUtil
445 .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
447 txInvoker.invoke(new TransactionCommand() {
449 public void execute(ReadWriteTransaction transaction) {
450 Optional<Node> ovsdbNodeOpt = SouthboundUtil.readNode(transaction, nodeIid);
451 if (ovsdbNodeOpt.isPresent()) {
452 Node ovsdbNode = ovsdbNodeOpt.get();
453 OvsdbNodeAugmentation nodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
454 if (nodeAugmentation != null) {
455 if (nodeAugmentation.getManagedNodeEntry() != null) {
456 for (ManagedNodeEntry managedNode : nodeAugmentation.getManagedNodeEntry()) {
458 LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
461 LOG.debug("{} had no managed nodes", ovsdbNode.getNodeId().getValue());
464 transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
471 private OpenVSwitch getOpenVswitchTableEntry(OvsdbConnectionInstance connectionInstance) {
472 DatabaseSchema dbSchema = null;
473 OpenVSwitch openVSwitchRow = null;
475 dbSchema = connectionInstance.getSchema(OvsdbSchemaContants.DATABASE_NAME).get();
476 } catch (InterruptedException | ExecutionException e) {
477 LOG.warn("Not able to fetch schema for database {} from device {}",
478 OvsdbSchemaContants.DATABASE_NAME,connectionInstance.getConnectionInfo(),e);
480 if (dbSchema != null) {
481 GenericTableSchema openVSwitchSchema = TyperUtils.getTableSchema(dbSchema, OpenVSwitch.class);
483 List<String> openVSwitchTableColumn = new ArrayList<>();
484 openVSwitchTableColumn.addAll(openVSwitchSchema.getColumns());
485 Select<GenericTableSchema> selectOperation = op.select(openVSwitchSchema);
486 selectOperation.setColumns(openVSwitchTableColumn);
488 List<Operation> operations = new ArrayList<>();
489 operations.add(selectOperation);
490 operations.add(op.comment("Fetching Open_VSwitch table rows"));
492 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
493 if (results != null ) {
494 OperationResult selectResult = results.get(0);
495 openVSwitchRow = TyperUtils.getTypedRowWrapper(
496 dbSchema,OpenVSwitch.class,selectResult.getRows().get(0));
499 } catch (InterruptedException | ExecutionException e) {
500 LOG.warn("Not able to fetch OpenVswitch table row from device {}",
501 connectionInstance.getConnectionInfo(),e);
504 return openVSwitchRow;
507 private Entity getEntityFromConnectionInstance(@Nonnull OvsdbConnectionInstance ovsdbConnectionInstance) {
508 InstanceIdentifier<Node> iid = ovsdbConnectionInstance.getInstanceIdentifier();
510 /* Switch initiated connection won't have iid, till it gets OpenVSwitch
511 * table update but update callback is always registered after ownership
512 * is granted. So we are explicitly fetch the row here to get the iid.
514 OpenVSwitch openvswitchRow = getOpenVswitchTableEntry(ovsdbConnectionInstance);
515 iid = SouthboundMapper.getInstanceIdentifier(openvswitchRow);
516 LOG.info("InstanceIdentifier {} generated for device "
517 + "connection {}",iid,ovsdbConnectionInstance.getConnectionInfo());
518 ovsdbConnectionInstance.setInstanceIdentifier(iid);
520 YangInstanceIdentifier entityId = SouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
521 Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
522 LOG.debug("Entity {} created for device connection {}",
523 deviceEntity, ovsdbConnectionInstance.getConnectionInfo());
527 private OvsdbConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
528 return entityConnectionMap.get(entity);
531 private void registerEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
533 Entity candidateEntity = getEntityFromConnectionInstance(ovsdbConnectionInstance);
534 entityConnectionMap.put(candidateEntity, ovsdbConnectionInstance);
535 ovsdbConnectionInstance.setConnectedEntity(candidateEntity);
537 EntityOwnershipCandidateRegistration registration =
538 entityOwnershipService.registerCandidate(candidateEntity);
539 ovsdbConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
540 LOG.info("OVSDB entity {} is registered for ownership.", candidateEntity);
542 //If entity already has owner, it won't get notification from EntityOwnershipService
543 //so cache the connection instances.
544 Optional<EntityOwnershipState> ownershipStateOpt =
545 entityOwnershipService.getOwnershipState(candidateEntity);
546 if (ownershipStateOpt.isPresent()) {
547 EntityOwnershipState ownershipState = ownershipStateOpt.get();
548 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
549 LOG.info("OVSDB entity {} is already owned by other southbound plugin "
550 + "instance, so *this* instance is NOT an OWNER of the device",
551 ovsdbConnectionInstance.getConnectionInfo());
552 putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
555 } catch (CandidateAlreadyRegisteredException e) {
556 LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
561 private void unregisterEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
562 ovsdbConnectionInstance.closeDeviceOwnershipCandidateRegistration();
563 entityConnectionMap.remove(ovsdbConnectionInstance.getConnectedEntity());
566 private void retryConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode,
567 ConnectionReconciliationTriggers trigger) {
568 final ReconciliationTask task = new ConnectionReconciliationTask(
569 reconciliationManager,
574 if (reconciliationManager.isEnqueued(task)) {
578 case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
579 reconciliationManager.enqueueForRetry(task);
583 ReadOnlyTransaction tx = db.newReadOnlyTransaction();
584 CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture =
585 tx.read(LogicalDatastoreType.CONFIGURATION, iid);
587 final OvsdbConnectionManager connectionManager = this;
588 Futures.addCallback(readNodeFuture, new FutureCallback<Optional<Node>>() {
590 public void onSuccess(@Nullable Optional<Node> node) {
591 if (node.isPresent()) {
592 LOG.info("Disconnected/Failed connection {} was controller initiated, attempting "
593 + "reconnection", ovsdbNode.getConnectionInfo());
594 reconciliationManager.enqueue(task);
597 LOG.debug("Connection {} was switch initiated, no reconciliation is required",
598 iid.firstKeyOf(Node.class).getNodeId());
603 public void onFailure(Throwable throwable) {
604 LOG.warn("Read Config/DS for Node failed! {}", iid, throwable);
614 private void reconcileBridgeConfigurations(final OvsdbConnectionInstance client) {
615 final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
616 final ReconciliationTask task = new BridgeConfigReconciliationTask(
617 reconciliationManager, OvsdbConnectionManager.this, nodeIid, client);
619 reconciliationManager.enqueue(task);
622 private class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
623 private OvsdbConnectionManager cm;
624 private EntityOwnershipListenerRegistration listenerRegistration;
626 OvsdbDeviceEntityOwnershipListener(OvsdbConnectionManager cm, EntityOwnershipService entityOwnershipService) {
628 listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
631 public void close() {
632 listenerRegistration.close();
636 public void ownershipChanged(EntityOwnershipChange ownershipChange) {
637 cm.handleOwnershipChanged(ownershipChange);
641 private enum ConnectionReconciliationTriggers {
643 Reconciliation trigger for scenario where controller's attempt
644 to connect to switch fails on config data store notification
646 ON_CONTROLLER_INITIATED_CONNECTION_FAILURE,
649 Reconciliation trigger for the scenario where controller
650 initiated connection disconnects.