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;
88 private final InstanceIdentifierCodec instanceIdentifierCodec;
90 public OvsdbConnectionManager(DataBroker db,TransactionInvoker txInvoker,
91 EntityOwnershipService entityOwnershipService,
92 OvsdbConnection ovsdbConnection,
93 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(@Nonnull 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());
111 List<String> databases = new ArrayList<>();
113 databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
114 if (databases.contains(SouthboundConstants.OPEN_V_SWITCH)) {
115 OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
116 // Register Cluster Ownership for ConnectionInfo
117 registerEntityForOwnership(client);
119 } catch (InterruptedException | ExecutionException | TimeoutException e) {
120 LOG.warn("Unable to fetch Database list from device {}. Disconnecting from the device.",
121 externalClient.getConnectionInfo().getRemoteAddress(), e);
122 externalClient.disconnect();
127 public OvsdbConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
128 LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
129 externalClient.getConnectionInfo().getRemotePort());
130 ConnectionInfo key = SouthboundMapper.createConnectionInfo(externalClient);
131 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
133 // Check if existing ovsdbConnectionInstance for the OvsdbClient present.
134 // In such cases, we will see if the ovsdbConnectionInstance has same externalClient.
135 if (ovsdbConnectionInstance != null) {
136 if (ovsdbConnectionInstance.hasOvsdbClient(externalClient)) {
137 LOG.warn("OVSDB Connection Instance {} already exists for client {}", key, externalClient);
138 return ovsdbConnectionInstance;
140 LOG.warn("OVSDB Connection Instance {} being replaced with client {}", key, externalClient);
142 // Unregister Cluster Ownership for ConnectionInfo
143 // Because the ovsdbConnectionInstance is about to be completely replaced!
144 unregisterEntityForOwnership(ovsdbConnectionInstance);
146 ovsdbConnectionInstance.disconnect();
148 removeConnectionInstance(key);
150 stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
153 ovsdbConnectionInstance = new OvsdbConnectionInstance(key, externalClient, txInvoker,
154 getInstanceIdentifier(key));
155 ovsdbConnectionInstance.createTransactInvokers();
156 return ovsdbConnectionInstance;
160 public void disconnected(OvsdbClient client) {
161 LOG.info("Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
162 client.getConnectionInfo().getType(),
163 client.getConnectionInfo().getRemoteAddress(),
164 client.getConnectionInfo().getRemotePort(),
165 client.getConnectionInfo().getLocalAddress(),
166 client.getConnectionInfo().getLocalPort());
167 ConnectionInfo key = SouthboundMapper.createConnectionInfo(client);
168 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
169 if (ovsdbConnectionInstance != null) {
170 // Unregister Entity ownership as soon as possible ,so this instance should
171 // not be used as a candidate in Entity election (given that this instance is
172 // about to disconnect as well), if current owner get disconnected from
174 unregisterEntityForOwnership(ovsdbConnectionInstance);
176 txInvoker.invoke(new OvsdbNodeRemoveCommand(ovsdbConnectionInstance, null, null));
178 removeConnectionInstance(key);
180 //Controller initiated connection can be terminated from switch side.
181 //So cleanup the instance identifier cache.
182 removeInstanceIdentifier(key);
183 stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
184 retryConnection(ovsdbConnectionInstance.getInstanceIdentifier(),
185 ovsdbConnectionInstance.getOvsdbNodeAugmentation(),
186 ConnectionReconciliationTriggers.ON_DISCONNECT);
188 LOG.warn("disconnected : Connection instance not found for OVSDB Node {} ", key);
190 LOG.trace("OvsdbConnectionManager: exit disconnected client: {}", client);
193 public OvsdbClient connect(InstanceIdentifier<Node> iid,
194 OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException, ConnectException {
195 LOG.info("Connecting to {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
197 // TODO handle case where we already have a connection
198 // TODO use transaction chains to handle ordering issues between disconnected
199 // TODO and connected when writing to the operational store
200 InetAddress ip = SouthboundMapper.createInetAddress(ovsdbNode.getConnectionInfo().getRemoteIp());
201 OvsdbClient client = ovsdbConnection.connect(ip,
202 ovsdbNode.getConnectionInfo().getRemotePort().getValue());
203 // For connections from the controller to the ovs instance, the library doesn't call
204 // this method for us
205 if (client != null) {
206 putInstanceIdentifier(ovsdbNode.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
207 OvsdbConnectionInstance ovsdbConnectionInstance = connectedButCallBacksNotRegistered(client);
208 ovsdbConnectionInstance.setOvsdbNodeAugmentation(ovsdbNode);
210 // Register Cluster Ownership for ConnectionInfo
211 registerEntityForOwnership(ovsdbConnectionInstance);
213 LOG.warn("Failed to connect to OVSDB Node {}", ovsdbNode.getConnectionInfo());
218 public void disconnect(OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
219 LOG.info("Disconnecting from {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
220 OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
221 if (client != null) {
222 // Unregister Cluster Onwership for ConnectionInfo
223 unregisterEntityForOwnership(client);
227 removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
229 stopBridgeConfigReconciliationIfActive(client.getInstanceIdentifier());
231 LOG.debug("disconnect : connection instance not found for {}",ovsdbNode.getConnectionInfo());
235 /* public void init(ConnectionInfo key) {
236 OvsdbConnectionInstance client = getConnectionInstance(key);
238 // TODO (FF): make sure that this cluster instance is the 'entity owner' fo the given OvsdbConnectionInstance ?
240 if (client != null) {
242 * Note: registerCallbacks() is idemPotent... so if you call it repeatedly all is safe,
243 * it only registersCallbacks on the *first* call.
245 client.registerCallbacks();
250 public void close() {
251 if (ovsdbDeviceEntityOwnershipListener != null) {
252 ovsdbDeviceEntityOwnershipListener.close();
255 for (OvsdbConnectionInstance client: clients.values()) {
260 private void putConnectionInstance(ConnectionInfo key,OvsdbConnectionInstance instance) {
261 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
262 clients.put(connectionInfo, instance);
265 private void removeConnectionInstance(ConnectionInfo key) {
266 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
267 clients.remove(connectionInfo);
270 private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
271 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
272 instanceIdentifiers.put(connectionInfo, iid);
275 private void removeInstanceIdentifier(ConnectionInfo key) {
276 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
277 instanceIdentifiers.remove(connectionInfo);
280 public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
281 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
282 return instanceIdentifiers.get(connectionInfo);
285 public OvsdbConnectionInstance getConnectionInstance(ConnectionInfo key) {
286 ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
287 return clients.get(connectionInfo);
290 public OvsdbConnectionInstance getConnectionInstance(OvsdbBridgeAttributes mn) {
291 Optional<OvsdbNodeAugmentation> optional = SouthboundUtil.getManagingNode(db, mn);
292 if (optional.isPresent()) {
293 return getConnectionInstance(optional.get().getConnectionInfo());
299 public OvsdbConnectionInstance getConnectionInstance(Node node) {
300 Preconditions.checkNotNull(node);
301 OvsdbNodeAugmentation ovsdbNode = node.getAugmentation(OvsdbNodeAugmentation.class);
302 OvsdbBridgeAugmentation ovsdbManagedNode = node.getAugmentation(OvsdbBridgeAugmentation.class);
303 if (ovsdbNode != null) {
304 return getConnectionInstance(ovsdbNode.getConnectionInfo());
305 } else if (ovsdbManagedNode != null) {
306 return getConnectionInstance(ovsdbManagedNode);
308 LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
313 public OvsdbConnectionInstance getConnectionInstance(InstanceIdentifier<Node> nodePath) {
315 ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
316 CheckedFuture<Optional<Node>, ReadFailedException> nodeFuture = transaction.read(
317 LogicalDatastoreType.OPERATIONAL, nodePath);
319 Optional<Node> optional = nodeFuture.get();
320 if (optional.isPresent()) {
321 return this.getConnectionInstance(optional.get());
323 LOG.debug("Node was not found on the path in the operational DS: {}", nodePath);
326 } catch (InterruptedException | ExecutionException e) {
327 LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
332 public OvsdbClient getClient(ConnectionInfo connectionInfo) {
333 return getConnectionInstance(connectionInfo).getOvsdbClient();
336 public OvsdbClient getClient(OvsdbBridgeAttributes mn) {
337 return getConnectionInstance(mn).getOvsdbClient();
340 public OvsdbClient getClient(Node node) {
341 return getConnectionInstance(node).getOvsdbClient();
344 public Boolean getHasDeviceOwnership(ConnectionInfo connectionInfo) {
345 OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(connectionInfo);
346 if (ovsdbConnectionInstance == null) {
347 return Boolean.FALSE;
349 return ovsdbConnectionInstance.getHasDeviceOwnership();
352 public void reconcileConnection(InstanceIdentifier<Node> iid, OvsdbNodeAugmentation ovsdbNode) {
353 this.retryConnection(iid, ovsdbNode,
354 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
358 public void stopConnectionReconciliationIfActive(InstanceIdentifier<?> iid, OvsdbNodeAugmentation ovsdbNode) {
359 final ReconciliationTask task = new ConnectionReconciliationTask(
360 reconciliationManager,
364 reconciliationManager.dequeue(task);
367 public void stopBridgeConfigReconciliationIfActive(InstanceIdentifier<?> iid) {
368 final ReconciliationTask task =
369 new BridgeConfigReconciliationTask(reconciliationManager, this, iid, null, instanceIdentifierCodec);
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(instanceIdentifierCodec);
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>) instanceIdentifierCodec.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(instanceIdentifierCodec, openvswitchRow);
515 LOG.info("InstanceIdentifier {} generated for device "
516 + "connection {}",iid,ovsdbConnectionInstance.getConnectionInfo());
517 ovsdbConnectionInstance.setInstanceIdentifier(iid);
519 YangInstanceIdentifier entityId = instanceIdentifierCodec.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, instanceIdentifierCodec);
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.