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);
373 private void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
374 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
375 LOG.debug("handleOwnershipChanged: {} event received for device {}",
376 ownershipChange, ovsdbConnectionInstance != null ? ovsdbConnectionInstance.getConnectionInfo()
377 : "that's currently NOT registered by *this* southbound plugin instance");
379 if (ovsdbConnectionInstance == null) {
380 if (ownershipChange.isOwner()) {
381 LOG.warn("handleOwnershipChanged: *this* instance is elected as an owner of the device {} but it "
382 + "is NOT registered for ownership", ownershipChange.getEntity());
384 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
385 // that instance registered for the device ownership or not. It is to make sure that
386 // If all the controller instance that was connected to the device are down, so the
387 // running instance can clear up the operational data store even though it was not
388 // connected to the device.
389 LOG.debug("handleOwnershipChanged: No connection instance found for {}", ownershipChange.getEntity());
392 // If entity has no owner, clean up the operational data store (it's possible because owner controller
393 // might went down abruptly and didn't get a chance to clean up the operational data store.
394 if (!ownershipChange.hasOwner()) {
395 LOG.info("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
396 cleanEntityOperationalData(ownershipChange.getEntity());
400 //Connection detail need to be cached, irrespective of ownership result.
401 putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
403 if (ownershipChange.isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
404 LOG.info("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
405 ovsdbConnectionInstance.getConnectionInfo(), ovsdbConnectionInstance.getHasDeviceOwnership()
406 ? SouthboundConstants.OwnershipStates.OWNER.getState()
407 : SouthboundConstants.OwnershipStates.NONOWNER.getState());
411 ovsdbConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
412 // You were not an owner, but now you are
413 if (ownershipChange.isOwner()) {
414 LOG.info("handleOwnershipChanged: *this* southbound plugin instance is an OWNER of the device {}",
415 ovsdbConnectionInstance.getConnectionInfo());
417 //*this* instance of southbound plugin is owner of the device,
418 //so register for monitor callbacks
419 ovsdbConnectionInstance.registerCallbacks();
421 reconcileBridgeConfigurations(ovsdbConnectionInstance);
423 //You were owner of the device, but now you are not. With the current ownership
424 //grant mechanism, this scenario should not occur. Because this scenario will occur
425 //when this controller went down or switch flap the connection, but in both the case
426 //it will go through the re-registration process. We need to implement this condition
427 //when clustering service implement a ownership grant strategy which can revoke the
428 //device ownership for load balancing the devices across the instances.
429 //Once this condition occur, we should unregister the callback.
430 LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}."
431 + "This should NOT happen.",
432 ovsdbConnectionInstance.getNodeId().getValue());
436 private void cleanEntityOperationalData(Entity entity) {
438 //Do explicit cleanup rather than using OvsdbNodeRemoveCommand, because there
439 // are chances that other controller instance went down abruptly and it does
440 // not clear manager entry, which OvsdbNodeRemoveCommand look for before cleanup.
442 @SuppressWarnings("unchecked") final InstanceIdentifier<Node> nodeIid =
443 (InstanceIdentifier<Node>) SouthboundUtil
444 .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
446 txInvoker.invoke(new TransactionCommand() {
448 public void execute(ReadWriteTransaction transaction) {
449 Optional<Node> ovsdbNodeOpt = SouthboundUtil.readNode(transaction, nodeIid);
450 if (ovsdbNodeOpt.isPresent()) {
451 Node ovsdbNode = ovsdbNodeOpt.get();
452 OvsdbNodeAugmentation nodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
453 if (nodeAugmentation != null) {
454 if (nodeAugmentation.getManagedNodeEntry() != null) {
455 for (ManagedNodeEntry managedNode : nodeAugmentation.getManagedNodeEntry()) {
457 LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
460 LOG.debug("{} had no managed nodes", ovsdbNode.getNodeId().getValue());
463 transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
470 private OpenVSwitch getOpenVswitchTableEntry(OvsdbConnectionInstance connectionInstance) {
471 DatabaseSchema dbSchema = null;
472 OpenVSwitch openVSwitchRow = null;
474 dbSchema = connectionInstance.getSchema(OvsdbSchemaContants.DATABASE_NAME).get();
475 } catch (InterruptedException | ExecutionException e) {
476 LOG.warn("Not able to fetch schema for database {} from device {}",
477 OvsdbSchemaContants.DATABASE_NAME,connectionInstance.getConnectionInfo(),e);
479 if (dbSchema != null) {
480 GenericTableSchema openVSwitchSchema = TyperUtils.getTableSchema(dbSchema, OpenVSwitch.class);
482 List<String> openVSwitchTableColumn = new ArrayList<>();
483 openVSwitchTableColumn.addAll(openVSwitchSchema.getColumns());
484 Select<GenericTableSchema> selectOperation = op.select(openVSwitchSchema);
485 selectOperation.setColumns(openVSwitchTableColumn);
487 List<Operation> operations = new ArrayList<>();
488 operations.add(selectOperation);
489 operations.add(op.comment("Fetching Open_VSwitch table rows"));
491 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
492 if (results != null ) {
493 OperationResult selectResult = results.get(0);
494 openVSwitchRow = TyperUtils.getTypedRowWrapper(
495 dbSchema,OpenVSwitch.class,selectResult.getRows().get(0));
498 } catch (InterruptedException | ExecutionException e) {
499 LOG.warn("Not able to fetch OpenVswitch table row from device {}",
500 connectionInstance.getConnectionInfo(),e);
503 return openVSwitchRow;
506 private Entity getEntityFromConnectionInstance(@Nonnull OvsdbConnectionInstance ovsdbConnectionInstance) {
507 InstanceIdentifier<Node> iid = ovsdbConnectionInstance.getInstanceIdentifier();
509 /* Switch initiated connection won't have iid, till it gets OpenVSwitch
510 * table update but update callback is always registered after ownership
511 * is granted. So we are explicitly fetch the row here to get the iid.
513 OpenVSwitch openvswitchRow = getOpenVswitchTableEntry(ovsdbConnectionInstance);
514 iid = SouthboundMapper.getInstanceIdentifier(openvswitchRow);
515 LOG.info("InstanceIdentifier {} generated for device "
516 + "connection {}",iid,ovsdbConnectionInstance.getConnectionInfo());
517 ovsdbConnectionInstance.setInstanceIdentifier(iid);
519 YangInstanceIdentifier entityId = SouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
520 Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
521 LOG.debug("Entity {} created for device connection {}",
522 deviceEntity, ovsdbConnectionInstance.getConnectionInfo());
526 private OvsdbConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
527 return entityConnectionMap.get(entity);
530 private void registerEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
532 Entity candidateEntity = getEntityFromConnectionInstance(ovsdbConnectionInstance);
533 entityConnectionMap.put(candidateEntity, ovsdbConnectionInstance);
534 ovsdbConnectionInstance.setConnectedEntity(candidateEntity);
536 EntityOwnershipCandidateRegistration registration =
537 entityOwnershipService.registerCandidate(candidateEntity);
538 ovsdbConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
539 LOG.info("OVSDB entity {} is registered for ownership.", candidateEntity);
541 //If entity already has owner, it won't get notification from EntityOwnershipService
542 //so cache the connection instances.
543 Optional<EntityOwnershipState> ownershipStateOpt =
544 entityOwnershipService.getOwnershipState(candidateEntity);
545 if (ownershipStateOpt.isPresent()) {
546 EntityOwnershipState ownershipState = ownershipStateOpt.get();
547 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
548 LOG.info("OVSDB entity {} is already owned by other southbound plugin "
549 + "instance, so *this* instance is NOT an OWNER of the device",
550 ovsdbConnectionInstance.getConnectionInfo());
551 putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
554 } catch (CandidateAlreadyRegisteredException e) {
555 LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
560 private void unregisterEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
561 ovsdbConnectionInstance.closeDeviceOwnershipCandidateRegistration();
562 entityConnectionMap.remove(ovsdbConnectionInstance.getConnectedEntity());
565 private void retryConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode,
566 ConnectionReconciliationTriggers trigger) {
567 final ReconciliationTask task = new ConnectionReconciliationTask(
568 reconciliationManager,
573 if (reconciliationManager.isEnqueued(task)) {
577 case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
578 reconciliationManager.enqueueForRetry(task);
582 ReadOnlyTransaction tx = db.newReadOnlyTransaction();
583 CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture =
584 tx.read(LogicalDatastoreType.CONFIGURATION, iid);
586 final OvsdbConnectionManager connectionManager = this;
587 Futures.addCallback(readNodeFuture, new FutureCallback<Optional<Node>>() {
589 public void onSuccess(@Nullable Optional<Node> node) {
590 if (node.isPresent()) {
591 LOG.info("Disconnected/Failed connection {} was controller initiated, attempting "
592 + "reconnection", ovsdbNode.getConnectionInfo());
593 reconciliationManager.enqueue(task);
596 LOG.debug("Connection {} was switch initiated, no reconciliation is required",
597 iid.firstKeyOf(Node.class).getNodeId());
602 public void onFailure(Throwable throwable) {
603 LOG.warn("Read Config/DS for Node failed! {}", iid, throwable);
613 private void reconcileBridgeConfigurations(final OvsdbConnectionInstance client) {
614 final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
615 final ReconciliationTask task = new BridgeConfigReconciliationTask(
616 reconciliationManager, OvsdbConnectionManager.this, nodeIid, client);
618 reconciliationManager.enqueue(task);
621 private class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
622 private OvsdbConnectionManager cm;
623 private EntityOwnershipListenerRegistration listenerRegistration;
625 OvsdbDeviceEntityOwnershipListener(OvsdbConnectionManager cm, EntityOwnershipService entityOwnershipService) {
627 listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
630 public void close() {
631 listenerRegistration.close();
635 public void ownershipChanged(EntityOwnershipChange ownershipChange) {
636 cm.handleOwnershipChanged(ownershipChange);
640 private enum ConnectionReconciliationTriggers {
642 Reconciliation trigger for scenario where controller's attempt
643 to connect to switch fails on config data store notification
645 ON_CONTROLLER_INITIATED_CONNECTION_FAILURE,
648 Reconciliation trigger for the scenario where controller
649 initiated connection disconnects.