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 java.util.Objects.requireNonNull;
11 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.util.concurrent.FluentFuture;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
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.Optional;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.TimeoutException;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.opendaylight.mdsal.binding.api.DataBroker;
31 import org.opendaylight.mdsal.binding.api.ReadTransaction;
32 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
33 import org.opendaylight.mdsal.eos.binding.api.Entity;
34 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
35 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
36 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
37 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
38 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
39 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
40 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
41 import org.opendaylight.ovsdb.lib.OvsdbClient;
42 import org.opendaylight.ovsdb.lib.OvsdbConnection;
43 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
44 import org.opendaylight.ovsdb.lib.operations.Operation;
45 import org.opendaylight.ovsdb.lib.operations.OperationResult;
46 import org.opendaylight.ovsdb.lib.operations.Select;
47 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
48 import org.opendaylight.ovsdb.lib.schema.typed.TypedDatabaseSchema;
49 import org.opendaylight.ovsdb.schema.openvswitch.OpenVSwitch;
50 import org.opendaylight.ovsdb.southbound.reconciliation.ReconciliationManager;
51 import org.opendaylight.ovsdb.southbound.reconciliation.ReconciliationTask;
52 import org.opendaylight.ovsdb.southbound.reconciliation.configuration.BridgeConfigReconciliationTask;
53 import org.opendaylight.ovsdb.southbound.reconciliation.connection.ConnectionReconciliationTask;
54 import org.opendaylight.ovsdb.southbound.transactions.md.OvsdbNodeRemoveCommand;
55 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
56 import org.opendaylight.serviceutils.upgrade.UpgradeState;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntryKey;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
64 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 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<OvsdbClient, OvsdbClient> alreadyProcessedClients = new ConcurrentHashMap<>();
79 private final Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
80 new ConcurrentHashMap<>();
81 private final Map<InstanceIdentifier<Node>, OvsdbConnectionInstance> nodeIdVsConnectionInstance =
82 new ConcurrentHashMap<>();
83 private final Map<Entity, OvsdbConnectionInstance> entityConnectionMap =
84 new ConcurrentHashMap<>();
85 private final EntityOwnershipService entityOwnershipService;
86 private final OvsdbDeviceEntityOwnershipListener ovsdbDeviceEntityOwnershipListener;
87 private final OvsdbConnection ovsdbConnection;
88 private final ReconciliationManager reconciliationManager;
89 private final InstanceIdentifierCodec instanceIdentifierCodec;
90 private final UpgradeState upgradeState;
92 public OvsdbConnectionManager(final DataBroker db,final TransactionInvoker txInvoker,
93 final EntityOwnershipService entityOwnershipService,
94 final OvsdbConnection ovsdbConnection,
95 final InstanceIdentifierCodec instanceIdentifierCodec,
96 final UpgradeState upgradeState) {
98 this.txInvoker = txInvoker;
99 this.entityOwnershipService = entityOwnershipService;
100 this.ovsdbDeviceEntityOwnershipListener = new OvsdbDeviceEntityOwnershipListener(this, entityOwnershipService);
101 this.ovsdbConnection = ovsdbConnection;
102 this.reconciliationManager = new ReconciliationManager(db, instanceIdentifierCodec);
103 this.instanceIdentifierCodec = instanceIdentifierCodec;
104 this.upgradeState = upgradeState;
108 public void connected(final OvsdbClient externalClient) {
109 if (alreadyProcessedClients.containsKey(externalClient)) {
110 LOG.info("OvsdbConnectionManager Library already connected {} from {}:{} to {}:{} "
111 + "to this, hence skipping the processing",
112 externalClient.getConnectionInfo().getType(),
113 externalClient.getConnectionInfo().getRemoteAddress(),
114 externalClient.getConnectionInfo().getRemotePort(),
115 externalClient.getConnectionInfo().getLocalAddress(),
116 externalClient.getConnectionInfo().getLocalPort());
119 alreadyProcessedClients.put(externalClient, externalClient);
121 LOG.info("OvsdbConnectionManager connected {} from {}:{} to {}:{}",
122 externalClient.getConnectionInfo().getType(),
123 externalClient.getConnectionInfo().getRemoteAddress(),
124 externalClient.getConnectionInfo().getRemotePort(),
125 externalClient.getConnectionInfo().getLocalAddress(),
126 externalClient.getConnectionInfo().getLocalPort());
128 List<String> databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
129 if (databases.contains(SouthboundConstants.OPEN_V_SWITCH)) {
130 OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
131 // Register Cluster Ownership for ConnectionInfo
132 registerEntityForOwnership(client);
133 OvsdbOperGlobalListener.runAfterTimeoutIfNodeNotCreated(client.getInstanceIdentifier(), () -> {
134 externalClient.disconnect();
135 disconnected(externalClient);
138 } catch (InterruptedException | ExecutionException | TimeoutException e) {
139 LOG.warn("OvsdbConnectionManager Unable to fetch Database list from device {}."
140 + "Disconnecting from the device.", externalClient.getConnectionInfo().getRemoteAddress(), e);
141 externalClient.disconnect();
146 public OvsdbConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
147 LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
148 externalClient.getConnectionInfo().getRemotePort());
149 ConnectionInfo key = SouthboundMapper.createConnectionInfo(externalClient);
150 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
152 // Check if existing ovsdbConnectionInstance for the OvsdbClient present.
153 // In such cases, we will see if the ovsdbConnectionInstance has same externalClient.
154 if (ovsdbConnectionInstance != null) {
155 if (ovsdbConnectionInstance.hasOvsdbClient(externalClient)) {
156 LOG.warn("OVSDB Connection Instance {} already exists for client {}", key, externalClient);
157 return ovsdbConnectionInstance;
159 LOG.warn("OVSDB Connection Instance {} being replaced with client {}", key, externalClient);
161 // Unregister Cluster Ownership for ConnectionInfo
162 // Because the ovsdbConnectionInstance is about to be completely replaced!
163 unregisterEntityForOwnership(ovsdbConnectionInstance);
165 ovsdbConnectionInstance.disconnect();
167 removeConnectionInstance(key);
169 stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
172 ovsdbConnectionInstance = new OvsdbConnectionInstance(key, externalClient, txInvoker,
173 getInstanceIdentifier(key));
174 ovsdbConnectionInstance.createTransactInvokers();
175 return ovsdbConnectionInstance;
179 public void disconnected(final OvsdbClient client) {
180 alreadyProcessedClients.remove(client);
181 LOG.info("Ovsdb Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
182 client.getConnectionInfo().getType(),
183 client.getConnectionInfo().getRemoteAddress(),
184 client.getConnectionInfo().getRemotePort(),
185 client.getConnectionInfo().getLocalAddress(),
186 client.getConnectionInfo().getLocalPort());
187 ConnectionInfo key = SouthboundMapper.createConnectionInfo(client);
188 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
189 if (ovsdbConnectionInstance != null) {
190 // Unregister Entity ownership as soon as possible ,so this instance should
191 // not be used as a candidate in Entity election (given that this instance is
192 // about to disconnect as well), if current owner get disconnected from
194 if (ovsdbConnectionInstance.getHasDeviceOwnership()) {
195 LOG.info("Ovsdb Library disconnected {} this controller instance has ownership", key);
196 deleteOperNodeAndReleaseOwnership(ovsdbConnectionInstance);
198 LOG.info("Ovsdb Library disconnected {} this controller does not have ownership", key);
199 unregisterEntityForOwnership(ovsdbConnectionInstance);
201 removeConnectionInstance(key);
203 //Controller initiated connection can be terminated from switch side.
204 //So cleanup the instance identifier cache.
205 removeInstanceIdentifier(key);
206 nodeIdVsConnectionInstance.remove(ovsdbConnectionInstance.getInstanceIdentifier(),
207 ovsdbConnectionInstance);
208 stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
209 retryConnection(ovsdbConnectionInstance.getInstanceIdentifier(),
210 ovsdbConnectionInstance.getOvsdbNodeAugmentation(),
211 ConnectionReconciliationTriggers.ON_DISCONNECT);
213 LOG.warn("Ovsdb disconnected : Connection instance not found for OVSDB Node {} ", key);
215 LOG.trace("OvsdbConnectionManager: exit disconnected client: {}", client);
218 private void deleteOperNodeAndReleaseOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
219 ovsdbConnectionInstance.setHasDeviceOwnership(false);
220 final InstanceIdentifier nodeIid = ovsdbConnectionInstance.getInstanceIdentifier();
221 //remove the node from oper only if it has ownership
222 txInvoker.invoke(new OvsdbNodeRemoveCommand(ovsdbConnectionInstance, null, null) {
225 public void onSuccess() {
227 LOG.debug("Successfully removed node {} from oper", nodeIid);
228 //Giveup the ownership only after cleanup is done
229 unregisterEntityForOwnership(ovsdbConnectionInstance);
233 public void onFailure(final Throwable throwable) {
234 LOG.debug("Failed to remove node {} from oper", nodeIid);
235 super.onFailure(throwable);
236 unregisterEntityForOwnership(ovsdbConnectionInstance);
241 public OvsdbClient connect(final InstanceIdentifier<Node> iid,
242 final OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException, ConnectException {
243 LOG.info("Connecting to {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
245 // TODO handle case where we already have a connection
246 // TODO use transaction chains to handle ordering issues between disconnected
247 // TODO and connected when writing to the operational store
248 InetAddress ip = SouthboundMapper.createInetAddress(ovsdbNode.getConnectionInfo().getRemoteIp());
249 OvsdbClient client = ovsdbConnection.connect(ip,
250 ovsdbNode.getConnectionInfo().getRemotePort().getValue().toJava());
251 // For connections from the controller to the ovs instance, the library doesn't call
252 // this method for us
253 if (client != null) {
254 putInstanceIdentifier(ovsdbNode.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
255 OvsdbConnectionInstance ovsdbConnectionInstance = connectedButCallBacksNotRegistered(client);
256 ovsdbConnectionInstance.setOvsdbNodeAugmentation(ovsdbNode);
258 // Register Cluster Ownership for ConnectionInfo
259 registerEntityForOwnership(ovsdbConnectionInstance);
261 LOG.warn("Failed to connect to OVSDB Node {}", ovsdbNode.getConnectionInfo());
266 public void disconnect(final OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
267 LOG.info("Disconnecting from {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
268 OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
269 if (client != null) {
270 // Unregister Cluster Onwership for ConnectionInfo
271 deleteOperNodeAndReleaseOwnership(client);
275 removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
277 stopBridgeConfigReconciliationIfActive(client.getInstanceIdentifier());
279 LOG.debug("disconnect : connection instance not found for {}",ovsdbNode.getConnectionInfo());
283 /* public void init(ConnectionInfo key) {
284 OvsdbConnectionInstance client = getConnectionInstance(key);
286 // TODO (FF): make sure that this cluster instance is the 'entity owner' fo the given OvsdbConnectionInstance ?
288 if (client != null) {
290 * Note: registerCallbacks() is idemPotent... so if you call it repeatedly all is safe,
291 * it only registersCallbacks on the *first* call.
293 client.registerCallbacks();
298 public void close() {
299 if (ovsdbDeviceEntityOwnershipListener != null) {
300 ovsdbDeviceEntityOwnershipListener.close();
303 for (OvsdbConnectionInstance client: clients.values()) {
309 void putConnectionInstance(final ConnectionInfo key,final OvsdbConnectionInstance instance) {
310 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
311 clients.put(connectionInfo, instance);
314 private void removeConnectionInstance(final ConnectionInfo key) {
315 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
316 clients.remove(connectionInfo);
320 void putInstanceIdentifier(final ConnectionInfo key, final InstanceIdentifier<Node> iid) {
321 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
322 instanceIdentifiers.put(connectionInfo, iid);
325 private void removeInstanceIdentifier(final ConnectionInfo key) {
326 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
327 instanceIdentifiers.remove(connectionInfo);
330 public InstanceIdentifier<Node> getInstanceIdentifier(final ConnectionInfo key) {
331 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
332 return instanceIdentifiers.get(connectionInfo);
335 public OvsdbConnectionInstance getConnectionInstance(final ConnectionInfo key) {
336 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
337 return clients.get(connectionInfo);
340 public OvsdbConnectionInstance getConnectionInstance(final OvsdbBridgeAttributes mn) {
341 Optional<OvsdbNodeAugmentation> optional = SouthboundUtil.getManagingNode(db, mn);
342 if (optional.isPresent()) {
343 return getConnectionInstance(optional.get().getConnectionInfo());
349 public OvsdbConnectionInstance getConnectionInstance(final Node node) {
350 requireNonNull(node);
351 OvsdbNodeAugmentation ovsdbNode = node.augmentation(OvsdbNodeAugmentation.class);
352 OvsdbBridgeAugmentation ovsdbManagedNode = node.augmentation(OvsdbBridgeAugmentation.class);
353 if (ovsdbNode != null) {
354 return getConnectionInstance(ovsdbNode.getConnectionInfo());
355 } else if (ovsdbManagedNode != null) {
356 return getConnectionInstance(ovsdbManagedNode);
358 LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
363 public OvsdbConnectionInstance getConnectionInstance(final InstanceIdentifier<Node> nodePath) {
364 if (nodeIdVsConnectionInstance.get(nodePath) != null) {
365 return nodeIdVsConnectionInstance.get(nodePath);
368 ReadTransaction transaction = db.newReadOnlyTransaction();
369 FluentFuture<Optional<Node>> nodeFuture = transaction.read(
370 LogicalDatastoreType.OPERATIONAL, nodePath);
372 Optional<Node> optional = nodeFuture.get();
373 if (optional.isPresent()) {
374 return this.getConnectionInstance(optional.get());
376 LOG.debug("Node was not found on the path in the operational DS: {}", nodePath);
379 } catch (InterruptedException | ExecutionException e) {
380 LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
385 public OvsdbClient getClient(final ConnectionInfo connectionInfo) {
386 OvsdbConnectionInstance connectionInstance = getConnectionInstance(connectionInfo);
387 if (connectionInstance != null) {
388 return connectionInstance.getOvsdbClient();
393 public OvsdbClient getClient(final OvsdbBridgeAttributes mn) {
394 return getConnectionInstance(mn).getOvsdbClient();
397 public OvsdbClient getClient(final Node node) {
398 return getConnectionInstance(node).getOvsdbClient();
401 public Boolean getHasDeviceOwnership(final ConnectionInfo connectionInfo) {
402 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(connectionInfo);
403 if (ovsdbConnectionInstance == null) {
404 return Boolean.FALSE;
406 return ovsdbConnectionInstance.getHasDeviceOwnership();
409 public void reconcileConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode) {
410 this.retryConnection(iid, ovsdbNode,
411 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
415 public void stopConnectionReconciliationIfActive(final InstanceIdentifier<Node> iid,
416 final OvsdbNodeAugmentation ovsdbNode) {
417 final ReconciliationTask task = new ConnectionReconciliationTask(
418 reconciliationManager,
422 reconciliationManager.dequeue(task);
425 public void stopBridgeConfigReconciliationIfActive(final InstanceIdentifier<Node> iid) {
426 final ReconciliationTask task =
427 new BridgeConfigReconciliationTask(reconciliationManager, this, iid, null, instanceIdentifierCodec);
428 reconciliationManager.dequeue(task);
429 reconciliationManager.cancelTerminationPointReconciliation();
432 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
433 justification = "https://github.com/spotbugs/spotbugs/issues/811")
434 private void handleOwnershipChanged(final EntityOwnershipChange ownershipChange) {
435 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
436 LOG.debug("Ovsdb handleOwnershipChanged: {} event received for device {}",
437 ownershipChange, ovsdbConnectionInstance != null ? ovsdbConnectionInstance.getConnectionInfo()
438 : "that's currently NOT registered by *this* southbound plugin instance");
440 if (ovsdbConnectionInstance == null) {
441 if (ownershipChange.getState().isOwner()) {
442 LOG.warn("Ovsdb handleOwnershipChanged: *this* instance is elected as an owner of the device {} but it "
443 + "is NOT registered for ownership", ownershipChange.getEntity());
445 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
446 // that instance registered for the device ownership or not. It is to make sure that
447 // If all the controller instance that was connected to the device are down, so the
448 // running instance can clear up the operational data store even though it was not
449 // connected to the device.
450 LOG.debug("Ovsdb handleOwnershipChanged: No connection instance found for {}",
451 ownershipChange.getEntity());
454 // If entity has no owner, clean up the operational data store (it's possible because owner controller
455 // might went down abruptly and didn't get a chance to clean up the operational data store.
456 if (!ownershipChange.getState().hasOwner()) {
457 LOG.info("Ovsdb {} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
458 cleanEntityOperationalData(ownershipChange.getEntity());
462 //Connection detail need to be cached, irrespective of ownership result.
463 putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
465 if (ownershipChange.getState().isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
466 LOG.info("Ovsdb handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
467 ovsdbConnectionInstance.getConnectionInfo(), ovsdbConnectionInstance.getHasDeviceOwnership()
468 ? SouthboundConstants.OwnershipStates.OWNER.getState()
469 : SouthboundConstants.OwnershipStates.NONOWNER.getState());
473 ovsdbConnectionInstance.setHasDeviceOwnership(ownershipChange.getState().isOwner());
474 // You were not an owner, but now you are
475 if (ownershipChange.getState().isOwner()) {
476 LOG.info("Ovsdb handleOwnershipChanged: *this* southbound plugin instance is an OWNER of the device {}",
477 ovsdbConnectionInstance.getConnectionInfo());
479 //*this* instance of southbound plugin is owner of the device,
480 //so register for monitor callbacks
481 ovsdbConnectionInstance.registerCallbacks(instanceIdentifierCodec);
482 LOG.trace("Ovsdb isUpgradeInProgress {}", upgradeState.isUpgradeInProgress());
483 if (!upgradeState.isUpgradeInProgress()) {
484 reconcileBridgeConfigurations(ovsdbConnectionInstance);
487 //You were owner of the device, but now you are not. With the current ownership
488 //grant mechanism, this scenario should not occur. Because this scenario will occur
489 //when this controller went down or switch flap the connection, but in both the case
490 //it will go through the re-registration process. We need to implement this condition
491 //when clustering service implement a ownership grant strategy which can revoke the
492 //device ownership for load balancing the devices across the instances.
493 //Once this condition occur, we should unregister the callback.
494 LOG.error("Ovsdb handleOwnershipChanged: *this* southbound plugin instance is no longer"
495 + " the owner of device {}.This should NOT happen.",
496 ovsdbConnectionInstance.getNodeId().getValue());
500 private void cleanEntityOperationalData(final Entity entity) {
502 //Do explicit cleanup rather than using OvsdbNodeRemoveCommand, because there
503 // are chances that other controller instance went down abruptly and it does
504 // not clear manager entry, which OvsdbNodeRemoveCommand look for before cleanup.
506 @SuppressWarnings("unchecked")
507 final InstanceIdentifier<Node> nodeIid = (InstanceIdentifier<Node>) entity.getIdentifier();
509 txInvoker.invoke(transaction -> {
510 Optional<Node> ovsdbNodeOpt = SouthboundUtil.readNode(transaction, nodeIid);
511 if (ovsdbNodeOpt.isPresent()) {
512 Node ovsdbNode = ovsdbNodeOpt.get();
513 OvsdbNodeAugmentation nodeAugmentation = ovsdbNode.augmentation(OvsdbNodeAugmentation.class);
514 if (nodeAugmentation != null) {
515 Map<ManagedNodeEntryKey, ManagedNodeEntry> entries = nodeAugmentation.getManagedNodeEntry();
516 if (entries != null) {
517 for (ManagedNodeEntry managedNode : entries.values()) {
519 LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
522 LOG.debug("{} had no managed nodes", ovsdbNode.getNodeId().getValue());
525 transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
531 private static OpenVSwitch getOpenVswitchTableEntry(final OvsdbConnectionInstance connectionInstance) {
532 final TypedDatabaseSchema dbSchema;
534 dbSchema = connectionInstance.getSchema(OvsdbSchemaContants.DATABASE_NAME).get();
535 } catch (InterruptedException | ExecutionException e) {
536 LOG.warn("Ovsdb Not able to fetch schema for database {} from device {}",
537 OvsdbSchemaContants.DATABASE_NAME,connectionInstance.getConnectionInfo(),e);
541 final GenericTableSchema openVSwitchSchema = dbSchema.getTableSchema(OpenVSwitch.class);
542 final Select<GenericTableSchema> selectOperation = op.select(openVSwitchSchema);
543 selectOperation.setColumns(openVSwitchSchema.getColumnList());
545 List<Operation> operations = new ArrayList<>();
546 operations.add(selectOperation);
547 operations.add(op.comment("Fetching Open_VSwitch table rows"));
548 final List<OperationResult> results;
550 results = connectionInstance.transact(dbSchema, operations).get();
551 } catch (InterruptedException | ExecutionException e) {
552 LOG.warn("Ovsdb Not able to fetch OpenVswitch table row from device {}",
553 connectionInstance.getConnectionInfo(), e);
557 return results == null || results.isEmpty() ? null
558 : dbSchema.getTypedRowWrapper(OpenVSwitch.class, results.get(0).getRows().get(0));
561 private Entity getEntityFromConnectionInstance(@NonNull final OvsdbConnectionInstance ovsdbConnectionInstance) {
562 InstanceIdentifier<Node> iid = ovsdbConnectionInstance.getInstanceIdentifier();
564 /* Switch initiated connection won't have iid, till it gets OpenVSwitch
565 * table update but update callback is always registered after ownership
566 * is granted. So we are explicitly fetch the row here to get the iid.
568 OpenVSwitch openvswitchRow = getOpenVswitchTableEntry(ovsdbConnectionInstance);
569 iid = SouthboundMapper.getInstanceIdentifier(instanceIdentifierCodec, openvswitchRow);
570 LOG.info("Ovsdb InstanceIdentifier {} generated for device "
571 + "connection {}",iid,ovsdbConnectionInstance.getConnectionInfo());
572 ovsdbConnectionInstance.setInstanceIdentifier(iid);
574 Entity deviceEntity = new Entity(ENTITY_TYPE, iid);
575 LOG.debug("Ovsdb Entity {} created for device connection {}",
576 deviceEntity, ovsdbConnectionInstance.getConnectionInfo());
580 private OvsdbConnectionInstance getConnectionInstanceFromEntity(final Entity entity) {
581 return entityConnectionMap.get(entity);
584 private void registerEntityForOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
585 putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(), ovsdbConnectionInstance);
587 Entity candidateEntity = getEntityFromConnectionInstance(ovsdbConnectionInstance);
588 if (entityConnectionMap.containsKey(candidateEntity)) {
589 LOG.error("Ovsdb Old connection still hanging for {}", candidateEntity);
590 disconnected(ovsdbConnectionInstance.getOvsdbClient());
591 //TODO do cleanup for old connection or stale check
593 nodeIdVsConnectionInstance.put((InstanceIdentifier<Node>) candidateEntity.getIdentifier(),
594 ovsdbConnectionInstance);
595 entityConnectionMap.put(candidateEntity, ovsdbConnectionInstance);
596 ovsdbConnectionInstance.setConnectedEntity(candidateEntity);
598 EntityOwnershipCandidateRegistration registration =
599 entityOwnershipService.registerCandidate(candidateEntity);
600 ovsdbConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
601 LOG.info("OVSDB entity {} is registered for ownership.", candidateEntity);
603 } catch (CandidateAlreadyRegisteredException e) {
604 LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
606 //If entity already has owner, it won't get notification from EntityOwnershipService
607 java.util.Optional<EntityOwnershipState> ownershipStateOpt =
608 entityOwnershipService.getOwnershipState(candidateEntity);
609 if (ownershipStateOpt.isPresent()) {
610 EntityOwnershipState ownershipState = ownershipStateOpt.get();
611 if (ownershipState == EntityOwnershipState.OWNED_BY_OTHER) {
612 ovsdbConnectionInstance.setHasDeviceOwnership(false);
613 } else if (ownershipState == EntityOwnershipState.IS_OWNER) {
614 ovsdbConnectionInstance.setHasDeviceOwnership(true);
615 ovsdbConnectionInstance.registerCallbacks(instanceIdentifierCodec);
620 private void unregisterEntityForOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
621 ovsdbConnectionInstance.closeDeviceOwnershipCandidateRegistration();
622 entityConnectionMap.remove(ovsdbConnectionInstance.getConnectedEntity(), ovsdbConnectionInstance);
625 private void retryConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode,
626 final ConnectionReconciliationTriggers trigger) {
627 final ReconciliationTask task = new ConnectionReconciliationTask(
628 reconciliationManager,
633 if (reconciliationManager.isEnqueued(task)) {
637 case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
638 reconciliationManager.enqueueForRetry(task);
640 case ON_DISCONNECT: {
641 FluentFuture<Boolean> readNodeFuture;
642 try (ReadTransaction tx = db.newReadOnlyTransaction()) {
643 readNodeFuture = tx.exists(LogicalDatastoreType.CONFIGURATION, iid);
645 readNodeFuture.addCallback(new FutureCallback<Boolean>() {
647 public void onSuccess(final Boolean node) {
648 if (node.booleanValue()) {
649 LOG.info("Disconnected/Failed connection {} was controller initiated, attempting "
650 + "reconnection", ovsdbNode.getConnectionInfo());
651 reconciliationManager.enqueue(task);
654 LOG.debug("Connection {} was switch initiated, no reconciliation is required",
655 iid.firstKeyOf(Node.class).getNodeId());
660 public void onFailure(final Throwable throwable) {
661 LOG.warn("Read Config/DS for Node failed! {}", iid, throwable);
663 }, MoreExecutors.directExecutor());
671 public void reconcileBridgeConfigurations(final OvsdbConnectionInstance client) {
672 final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
673 final ReconciliationTask task = new BridgeConfigReconciliationTask(
674 reconciliationManager, OvsdbConnectionManager.this, nodeIid, client, instanceIdentifierCodec);
676 reconciliationManager.enqueue(task);
679 private static class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
680 private final OvsdbConnectionManager cm;
681 private final EntityOwnershipListenerRegistration listenerRegistration;
683 OvsdbDeviceEntityOwnershipListener(final OvsdbConnectionManager cm,
684 final EntityOwnershipService entityOwnershipService) {
686 listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
689 public void close() {
690 listenerRegistration.close();
694 public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
695 cm.handleOwnershipChanged(ownershipChange);
699 private enum ConnectionReconciliationTriggers {
701 Reconciliation trigger for scenario where controller's attempt
702 to connect to switch fails on config data store notification
704 ON_CONTROLLER_INITIATED_CONNECTION_FAILURE,
707 Reconciliation trigger for the scenario where controller
708 initiated connection disconnects.
713 public Map<ConnectionInfo, OvsdbConnectionInstance> getClients() {