2 * Copyright © 2014, 2017 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.annotations.VisibleForTesting;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
20 import java.net.ConnectException;
21 import java.net.InetAddress;
22 import java.net.UnknownHostException;
23 import java.util.ArrayList;
24 import java.util.List;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
32 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
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.mdsal.eos.binding.api.Entity;
36 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
37 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
38 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
39 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
40 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
41 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
42 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
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.TransactionInvoker;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
64 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
65 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoCloseable {
70 private final Map<ConnectionInfo, OvsdbConnectionInstance> clients =
71 new ConcurrentHashMap<>();
72 private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionManager.class);
73 private static final String ENTITY_TYPE = "ovsdb";
74 private static final int DB_FETCH_TIMEOUT = 1000;
76 private final DataBroker db;
77 private final TransactionInvoker txInvoker;
78 private final Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
79 new ConcurrentHashMap<>();
80 private final Map<InstanceIdentifier<Node>, OvsdbConnectionInstance> nodeIdVsConnectionInstance =
81 new ConcurrentHashMap<>();
82 private final Map<Entity, OvsdbConnectionInstance> entityConnectionMap =
83 new ConcurrentHashMap<>();
84 private final EntityOwnershipService entityOwnershipService;
85 private final OvsdbDeviceEntityOwnershipListener ovsdbDeviceEntityOwnershipListener;
86 private final OvsdbConnection ovsdbConnection;
87 private final ReconciliationManager reconciliationManager;
88 private final InstanceIdentifierCodec instanceIdentifierCodec;
90 public OvsdbConnectionManager(final DataBroker db,final TransactionInvoker txInvoker,
91 final EntityOwnershipService entityOwnershipService,
92 final OvsdbConnection ovsdbConnection,
93 final InstanceIdentifierCodec instanceIdentifierCodec) {
95 this.txInvoker = txInvoker;
96 this.entityOwnershipService = entityOwnershipService;
97 this.ovsdbDeviceEntityOwnershipListener = new OvsdbDeviceEntityOwnershipListener(this, entityOwnershipService);
98 this.ovsdbConnection = ovsdbConnection;
99 this.reconciliationManager = new ReconciliationManager(db, instanceIdentifierCodec);
100 this.instanceIdentifierCodec = instanceIdentifierCodec;
104 public void connected(final OvsdbClient externalClient) {
105 LOG.info("Library connected {} from {}:{} to {}:{}",
106 externalClient.getConnectionInfo().getType(),
107 externalClient.getConnectionInfo().getRemoteAddress(),
108 externalClient.getConnectionInfo().getRemotePort(),
109 externalClient.getConnectionInfo().getLocalAddress(),
110 externalClient.getConnectionInfo().getLocalPort());
112 List<String> databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
113 if (databases.contains(SouthboundConstants.OPEN_V_SWITCH)) {
114 OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
115 // Register Cluster Ownership for ConnectionInfo
116 registerEntityForOwnership(client);
118 } catch (InterruptedException | ExecutionException | TimeoutException e) {
119 LOG.warn("Unable to fetch Database list from device {}. Disconnecting from the device.",
120 externalClient.getConnectionInfo().getRemoteAddress(), e);
121 externalClient.disconnect();
126 public OvsdbConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
127 LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
128 externalClient.getConnectionInfo().getRemotePort());
129 ConnectionInfo key = SouthboundMapper.createConnectionInfo(externalClient);
130 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
132 // Check if existing ovsdbConnectionInstance for the OvsdbClient present.
133 // In such cases, we will see if the ovsdbConnectionInstance has same externalClient.
134 if (ovsdbConnectionInstance != null) {
135 if (ovsdbConnectionInstance.hasOvsdbClient(externalClient)) {
136 LOG.warn("OVSDB Connection Instance {} already exists for client {}", key, externalClient);
137 return ovsdbConnectionInstance;
139 LOG.warn("OVSDB Connection Instance {} being replaced with client {}", key, externalClient);
141 // Unregister Cluster Ownership for ConnectionInfo
142 // Because the ovsdbConnectionInstance is about to be completely replaced!
143 unregisterEntityForOwnership(ovsdbConnectionInstance);
145 ovsdbConnectionInstance.disconnect();
147 removeConnectionInstance(key);
149 stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
152 ovsdbConnectionInstance = new OvsdbConnectionInstance(key, externalClient, txInvoker,
153 getInstanceIdentifier(key));
154 ovsdbConnectionInstance.createTransactInvokers();
155 return ovsdbConnectionInstance;
159 public void disconnected(final OvsdbClient client) {
160 LOG.info("Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
161 client.getConnectionInfo().getType(),
162 client.getConnectionInfo().getRemoteAddress(),
163 client.getConnectionInfo().getRemotePort(),
164 client.getConnectionInfo().getLocalAddress(),
165 client.getConnectionInfo().getLocalPort());
166 ConnectionInfo key = SouthboundMapper.createConnectionInfo(client);
167 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
168 if (ovsdbConnectionInstance != null) {
169 // Unregister Entity ownership as soon as possible ,so this instance should
170 // not be used as a candidate in Entity election (given that this instance is
171 // about to disconnect as well), if current owner get disconnected from
173 if (ovsdbConnectionInstance.getHasDeviceOwnership()) {
174 LOG.info("Library disconnected {} this controller instance has ownership", key);
175 deleteOperNodeAndReleaseOwnership(ovsdbConnectionInstance);
177 LOG.info("Library disconnected {} this controller does not have ownership", key);
178 unregisterEntityForOwnership(ovsdbConnectionInstance);
180 removeConnectionInstance(key);
182 //Controller initiated connection can be terminated from switch side.
183 //So cleanup the instance identifier cache.
184 removeInstanceIdentifier(key);
185 nodeIdVsConnectionInstance.remove(ovsdbConnectionInstance.getInstanceIdentifier(),
186 ovsdbConnectionInstance);
187 stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
188 retryConnection(ovsdbConnectionInstance.getInstanceIdentifier(),
189 ovsdbConnectionInstance.getOvsdbNodeAugmentation(),
190 ConnectionReconciliationTriggers.ON_DISCONNECT);
192 LOG.warn("disconnected : Connection instance not found for OVSDB Node {} ", key);
194 LOG.trace("OvsdbConnectionManager: exit disconnected client: {}", client);
197 private void deleteOperNodeAndReleaseOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
198 ovsdbConnectionInstance.setHasDeviceOwnership(false);
199 final InstanceIdentifier nodeIid = ovsdbConnectionInstance.getInstanceIdentifier();
200 //remove the node from oper only if it has ownership
201 txInvoker.invoke(new OvsdbNodeRemoveCommand(ovsdbConnectionInstance, null, null) {
204 public void onSuccess() {
206 LOG.debug("Successfully removed node {} from oper", nodeIid);
207 //Giveup the ownership only after cleanup is done
208 unregisterEntityForOwnership(ovsdbConnectionInstance);
212 public void onFailure(final Throwable throwable) {
213 LOG.debug("Failed to remove node {} from oper", nodeIid);
214 super.onFailure(throwable);
215 unregisterEntityForOwnership(ovsdbConnectionInstance);
220 public OvsdbClient connect(final InstanceIdentifier<Node> iid,
221 final OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException, ConnectException {
222 LOG.info("Connecting to {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
224 // TODO handle case where we already have a connection
225 // TODO use transaction chains to handle ordering issues between disconnected
226 // TODO and connected when writing to the operational store
227 InetAddress ip = SouthboundMapper.createInetAddress(ovsdbNode.getConnectionInfo().getRemoteIp());
228 OvsdbClient client = ovsdbConnection.connect(ip,
229 ovsdbNode.getConnectionInfo().getRemotePort().getValue().toJava());
230 // For connections from the controller to the ovs instance, the library doesn't call
231 // this method for us
232 if (client != null) {
233 putInstanceIdentifier(ovsdbNode.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
234 OvsdbConnectionInstance ovsdbConnectionInstance = connectedButCallBacksNotRegistered(client);
235 ovsdbConnectionInstance.setOvsdbNodeAugmentation(ovsdbNode);
237 // Register Cluster Ownership for ConnectionInfo
238 registerEntityForOwnership(ovsdbConnectionInstance);
240 LOG.warn("Failed to connect to OVSDB Node {}", ovsdbNode.getConnectionInfo());
245 public void disconnect(final OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
246 LOG.info("Disconnecting from {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
247 OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
248 if (client != null) {
249 // Unregister Cluster Onwership for ConnectionInfo
250 deleteOperNodeAndReleaseOwnership(client);
254 removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
256 stopBridgeConfigReconciliationIfActive(client.getInstanceIdentifier());
258 LOG.debug("disconnect : connection instance not found for {}",ovsdbNode.getConnectionInfo());
262 /* public void init(ConnectionInfo key) {
263 OvsdbConnectionInstance client = getConnectionInstance(key);
265 // TODO (FF): make sure that this cluster instance is the 'entity owner' fo the given OvsdbConnectionInstance ?
267 if (client != null) {
269 * Note: registerCallbacks() is idemPotent... so if you call it repeatedly all is safe,
270 * it only registersCallbacks on the *first* call.
272 client.registerCallbacks();
277 public void close() {
278 if (ovsdbDeviceEntityOwnershipListener != null) {
279 ovsdbDeviceEntityOwnershipListener.close();
282 for (OvsdbConnectionInstance client: clients.values()) {
288 void putConnectionInstance(final ConnectionInfo key,final OvsdbConnectionInstance instance) {
289 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
290 clients.put(connectionInfo, instance);
293 private void removeConnectionInstance(final ConnectionInfo key) {
294 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
295 clients.remove(connectionInfo);
299 void putInstanceIdentifier(final ConnectionInfo key, final InstanceIdentifier<Node> iid) {
300 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
301 instanceIdentifiers.put(connectionInfo, iid);
304 private void removeInstanceIdentifier(final ConnectionInfo key) {
305 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
306 instanceIdentifiers.remove(connectionInfo);
309 public InstanceIdentifier<Node> getInstanceIdentifier(final ConnectionInfo key) {
310 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
311 return instanceIdentifiers.get(connectionInfo);
314 public OvsdbConnectionInstance getConnectionInstance(final ConnectionInfo key) {
315 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
316 return clients.get(connectionInfo);
319 public OvsdbConnectionInstance getConnectionInstance(final OvsdbBridgeAttributes mn) {
320 Optional<OvsdbNodeAugmentation> optional = SouthboundUtil.getManagingNode(db, mn);
321 if (optional.isPresent()) {
322 return getConnectionInstance(optional.get().getConnectionInfo());
328 public OvsdbConnectionInstance getConnectionInstance(final Node node) {
329 Preconditions.checkNotNull(node);
330 OvsdbNodeAugmentation ovsdbNode = node.augmentation(OvsdbNodeAugmentation.class);
331 OvsdbBridgeAugmentation ovsdbManagedNode = node.augmentation(OvsdbBridgeAugmentation.class);
332 if (ovsdbNode != null) {
333 return getConnectionInstance(ovsdbNode.getConnectionInfo());
334 } else if (ovsdbManagedNode != null) {
335 return getConnectionInstance(ovsdbManagedNode);
337 LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
342 public OvsdbConnectionInstance getConnectionInstance(final InstanceIdentifier<Node> nodePath) {
343 if (nodeIdVsConnectionInstance.get(nodePath) != null) {
344 return nodeIdVsConnectionInstance.get(nodePath);
347 ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
348 CheckedFuture<Optional<Node>, ReadFailedException> nodeFuture = transaction.read(
349 LogicalDatastoreType.OPERATIONAL, nodePath);
351 Optional<Node> optional = nodeFuture.get();
352 if (optional.isPresent()) {
353 return this.getConnectionInstance(optional.get());
355 LOG.debug("Node was not found on the path in the operational DS: {}", nodePath);
358 } catch (InterruptedException | ExecutionException e) {
359 LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
364 public OvsdbClient getClient(final ConnectionInfo connectionInfo) {
365 OvsdbConnectionInstance connectionInstance = getConnectionInstance(connectionInfo);
366 if (connectionInstance != null) {
367 return connectionInstance.getOvsdbClient();
372 public OvsdbClient getClient(final OvsdbBridgeAttributes mn) {
373 return getConnectionInstance(mn).getOvsdbClient();
376 public OvsdbClient getClient(final Node node) {
377 return getConnectionInstance(node).getOvsdbClient();
380 public Boolean getHasDeviceOwnership(final ConnectionInfo connectionInfo) {
381 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(connectionInfo);
382 if (ovsdbConnectionInstance == null) {
383 return Boolean.FALSE;
385 return ovsdbConnectionInstance.getHasDeviceOwnership();
388 public void reconcileConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode) {
389 this.retryConnection(iid, ovsdbNode,
390 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
394 public void stopConnectionReconciliationIfActive(final InstanceIdentifier<?> iid,
395 final OvsdbNodeAugmentation ovsdbNode) {
396 final ReconciliationTask task = new ConnectionReconciliationTask(
397 reconciliationManager,
401 reconciliationManager.dequeue(task);
404 public void stopBridgeConfigReconciliationIfActive(final InstanceIdentifier<?> iid) {
405 final ReconciliationTask task =
406 new BridgeConfigReconciliationTask(reconciliationManager, this, iid, null, instanceIdentifierCodec);
407 reconciliationManager.dequeue(task);
408 reconciliationManager.cancelTerminationPointReconciliation();
411 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
412 justification = "https://github.com/spotbugs/spotbugs/issues/811")
413 private void handleOwnershipChanged(final EntityOwnershipChange ownershipChange) {
414 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
415 LOG.debug("handleOwnershipChanged: {} event received for device {}",
416 ownershipChange, ovsdbConnectionInstance != null ? ovsdbConnectionInstance.getConnectionInfo()
417 : "that's currently NOT registered by *this* southbound plugin instance");
419 if (ovsdbConnectionInstance == null) {
420 if (ownershipChange.getState().isOwner()) {
421 LOG.warn("handleOwnershipChanged: *this* instance is elected as an owner of the device {} but it "
422 + "is NOT registered for ownership", ownershipChange.getEntity());
424 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
425 // that instance registered for the device ownership or not. It is to make sure that
426 // If all the controller instance that was connected to the device are down, so the
427 // running instance can clear up the operational data store even though it was not
428 // connected to the device.
429 LOG.debug("handleOwnershipChanged: No connection instance found for {}", ownershipChange.getEntity());
432 // If entity has no owner, clean up the operational data store (it's possible because owner controller
433 // might went down abruptly and didn't get a chance to clean up the operational data store.
434 if (!ownershipChange.getState().hasOwner()) {
435 LOG.info("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
436 cleanEntityOperationalData(ownershipChange.getEntity());
440 //Connection detail need to be cached, irrespective of ownership result.
441 putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
443 if (ownershipChange.getState().isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
444 LOG.info("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
445 ovsdbConnectionInstance.getConnectionInfo(), ovsdbConnectionInstance.getHasDeviceOwnership()
446 ? SouthboundConstants.OwnershipStates.OWNER.getState()
447 : SouthboundConstants.OwnershipStates.NONOWNER.getState());
451 ovsdbConnectionInstance.setHasDeviceOwnership(ownershipChange.getState().isOwner());
452 // You were not an owner, but now you are
453 if (ownershipChange.getState().isOwner()) {
454 LOG.info("handleOwnershipChanged: *this* southbound plugin instance is an OWNER of the device {}",
455 ovsdbConnectionInstance.getConnectionInfo());
457 //*this* instance of southbound plugin is owner of the device,
458 //so register for monitor callbacks
459 ovsdbConnectionInstance.registerCallbacks(instanceIdentifierCodec);
461 reconcileBridgeConfigurations(ovsdbConnectionInstance);
463 //You were owner of the device, but now you are not. With the current ownership
464 //grant mechanism, this scenario should not occur. Because this scenario will occur
465 //when this controller went down or switch flap the connection, but in both the case
466 //it will go through the re-registration process. We need to implement this condition
467 //when clustering service implement a ownership grant strategy which can revoke the
468 //device ownership for load balancing the devices across the instances.
469 //Once this condition occur, we should unregister the callback.
470 LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}."
471 + "This should NOT happen.",
472 ovsdbConnectionInstance.getNodeId().getValue());
476 private void cleanEntityOperationalData(final Entity entity) {
478 //Do explicit cleanup rather than using OvsdbNodeRemoveCommand, because there
479 // are chances that other controller instance went down abruptly and it does
480 // not clear manager entry, which OvsdbNodeRemoveCommand look for before cleanup.
482 @SuppressWarnings("unchecked")
483 final InstanceIdentifier<Node> nodeIid = (InstanceIdentifier<Node>) entity.getIdentifier();
485 txInvoker.invoke(transaction -> {
486 Optional<Node> ovsdbNodeOpt = SouthboundUtil.readNode(transaction, nodeIid);
487 if (ovsdbNodeOpt.isPresent()) {
488 Node ovsdbNode = ovsdbNodeOpt.get();
489 OvsdbNodeAugmentation nodeAugmentation = ovsdbNode.augmentation(OvsdbNodeAugmentation.class);
490 if (nodeAugmentation != null) {
491 if (nodeAugmentation.getManagedNodeEntry() != null) {
492 for (ManagedNodeEntry managedNode : nodeAugmentation.getManagedNodeEntry()) {
494 LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
497 LOG.debug("{} had no managed nodes", ovsdbNode.getNodeId().getValue());
500 transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
506 private OpenVSwitch getOpenVswitchTableEntry(final OvsdbConnectionInstance connectionInstance) {
507 DatabaseSchema dbSchema = null;
508 OpenVSwitch openVSwitchRow = null;
510 dbSchema = connectionInstance.getSchema(OvsdbSchemaContants.DATABASE_NAME).get();
511 } catch (InterruptedException | ExecutionException e) {
512 LOG.warn("Not able to fetch schema for database {} from device {}",
513 OvsdbSchemaContants.DATABASE_NAME,connectionInstance.getConnectionInfo(),e);
515 if (dbSchema != null) {
516 GenericTableSchema openVSwitchSchema = TyperUtils.getTableSchema(dbSchema, OpenVSwitch.class);
518 List<String> openVSwitchTableColumn = new ArrayList<>();
519 openVSwitchTableColumn.addAll(openVSwitchSchema.getColumns());
520 Select<GenericTableSchema> selectOperation = op.select(openVSwitchSchema);
521 selectOperation.setColumns(openVSwitchTableColumn);
523 List<Operation> operations = new ArrayList<>();
524 operations.add(selectOperation);
525 operations.add(op.comment("Fetching Open_VSwitch table rows"));
527 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
528 if (results != null) {
529 OperationResult selectResult = results.get(0);
530 openVSwitchRow = TyperUtils.getTypedRowWrapper(
531 dbSchema,OpenVSwitch.class,selectResult.getRows().get(0));
534 } catch (InterruptedException | ExecutionException e) {
535 LOG.warn("Not able to fetch OpenVswitch table row from device {}",
536 connectionInstance.getConnectionInfo(),e);
539 return openVSwitchRow;
542 private Entity getEntityFromConnectionInstance(@NonNull final OvsdbConnectionInstance ovsdbConnectionInstance) {
543 InstanceIdentifier<Node> iid = ovsdbConnectionInstance.getInstanceIdentifier();
545 /* Switch initiated connection won't have iid, till it gets OpenVSwitch
546 * table update but update callback is always registered after ownership
547 * is granted. So we are explicitly fetch the row here to get the iid.
549 OpenVSwitch openvswitchRow = getOpenVswitchTableEntry(ovsdbConnectionInstance);
550 iid = SouthboundMapper.getInstanceIdentifier(instanceIdentifierCodec, openvswitchRow);
551 LOG.info("InstanceIdentifier {} generated for device "
552 + "connection {}",iid,ovsdbConnectionInstance.getConnectionInfo());
553 ovsdbConnectionInstance.setInstanceIdentifier(iid);
555 Entity deviceEntity = new Entity(ENTITY_TYPE, iid);
556 LOG.debug("Entity {} created for device connection {}",
557 deviceEntity, ovsdbConnectionInstance.getConnectionInfo());
561 private OvsdbConnectionInstance getConnectionInstanceFromEntity(final Entity entity) {
562 return entityConnectionMap.get(entity);
565 private void registerEntityForOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
566 putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(), ovsdbConnectionInstance);
568 Entity candidateEntity = getEntityFromConnectionInstance(ovsdbConnectionInstance);
569 if (entityConnectionMap.containsKey(candidateEntity)) {
570 LOG.error("Old connection still hanging for {}", candidateEntity);
571 disconnected(ovsdbConnectionInstance.getOvsdbClient());
572 //TODO do cleanup for old connection or stale check
574 nodeIdVsConnectionInstance.put((InstanceIdentifier<Node>) candidateEntity.getIdentifier(),
575 ovsdbConnectionInstance);
576 entityConnectionMap.put(candidateEntity, ovsdbConnectionInstance);
577 ovsdbConnectionInstance.setConnectedEntity(candidateEntity);
579 EntityOwnershipCandidateRegistration registration =
580 entityOwnershipService.registerCandidate(candidateEntity);
581 ovsdbConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
582 LOG.info("OVSDB entity {} is registered for ownership.", candidateEntity);
584 } catch (CandidateAlreadyRegisteredException e) {
585 LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
587 //If entity already has owner, it won't get notification from EntityOwnershipService
588 java.util.Optional<EntityOwnershipState> ownershipStateOpt =
589 entityOwnershipService.getOwnershipState(candidateEntity);
590 if (ownershipStateOpt.isPresent()) {
591 EntityOwnershipState ownershipState = ownershipStateOpt.get();
592 if (ownershipState == EntityOwnershipState.OWNED_BY_OTHER) {
593 ovsdbConnectionInstance.setHasDeviceOwnership(false);
594 } else if (ownershipState == EntityOwnershipState.IS_OWNER) {
595 ovsdbConnectionInstance.setHasDeviceOwnership(true);
596 ovsdbConnectionInstance.registerCallbacks(instanceIdentifierCodec);
601 private void unregisterEntityForOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
602 ovsdbConnectionInstance.closeDeviceOwnershipCandidateRegistration();
603 entityConnectionMap.remove(ovsdbConnectionInstance.getConnectedEntity(), ovsdbConnectionInstance);
606 private void retryConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode,
607 final ConnectionReconciliationTriggers trigger) {
608 final ReconciliationTask task = new ConnectionReconciliationTask(
609 reconciliationManager,
614 if (reconciliationManager.isEnqueued(task)) {
618 case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
619 reconciliationManager.enqueueForRetry(task);
621 case ON_DISCONNECT: {
622 CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture;
623 try (ReadOnlyTransaction tx = db.newReadOnlyTransaction()) {
624 readNodeFuture = tx.read(LogicalDatastoreType.CONFIGURATION, iid);
626 Futures.addCallback(readNodeFuture, new FutureCallback<Optional<Node>>() {
628 public void onSuccess(final Optional<Node> node) {
629 if (node.isPresent()) {
630 LOG.info("Disconnected/Failed connection {} was controller initiated, attempting "
631 + "reconnection", ovsdbNode.getConnectionInfo());
632 reconciliationManager.enqueue(task);
635 LOG.debug("Connection {} was switch initiated, no reconciliation is required",
636 iid.firstKeyOf(Node.class).getNodeId());
641 public void onFailure(final Throwable throwable) {
642 LOG.warn("Read Config/DS for Node failed! {}", iid, throwable);
644 }, MoreExecutors.directExecutor());
652 private void reconcileBridgeConfigurations(final OvsdbConnectionInstance client) {
653 final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
654 final ReconciliationTask task = new BridgeConfigReconciliationTask(
655 reconciliationManager, OvsdbConnectionManager.this, nodeIid, client, instanceIdentifierCodec);
657 reconciliationManager.enqueue(task);
660 private static class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
661 private final OvsdbConnectionManager cm;
662 private final EntityOwnershipListenerRegistration listenerRegistration;
664 OvsdbDeviceEntityOwnershipListener(final OvsdbConnectionManager cm,
665 final EntityOwnershipService entityOwnershipService) {
667 listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
670 public void close() {
671 listenerRegistration.close();
675 public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
676 cm.handleOwnershipChanged(ownershipChange);
680 private enum ConnectionReconciliationTriggers {
682 Reconciliation trigger for scenario where controller's attempt
683 to connect to switch fails on config data store notification
685 ON_CONTROLLER_INITIATED_CONNECTION_FAILURE,
688 Reconciliation trigger for the scenario where controller
689 initiated connection disconnects.