2 * Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. 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
9 package org.opendaylight.ovsdb.hwvtepsouthbound;
11 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
13 import java.net.InetAddress;
14 import java.net.UnknownHostException;
15 import java.util.ArrayList;
16 import java.util.List;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ExecutionException;
21 import javax.annotation.Nonnull;
23 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
24 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
25 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
26 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
27 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
28 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
29 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
30 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
31 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
32 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
33 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
34 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.HwvtepGlobalRemoveCommand;
35 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionCommand;
36 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvoker;
37 import org.opendaylight.ovsdb.lib.OvsdbClient;
38 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
39 import org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService;
40 import org.opendaylight.ovsdb.lib.operations.Operation;
41 import org.opendaylight.ovsdb.lib.operations.OperationResult;
42 import org.opendaylight.ovsdb.lib.operations.Select;
43 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
44 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
45 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
46 import org.opendaylight.ovsdb.schema.hardwarevtep.Global;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalSwitchAttributes;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.PhysicalSwitchAugmentation;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ConnectionInfo;
51 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
52 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
57 import com.google.common.base.Optional;
58 import com.google.common.base.Preconditions;
60 public class HwvtepConnectionManager implements OvsdbConnectionListener, AutoCloseable{
61 private Map<ConnectionInfo, HwvtepConnectionInstance> clients = new ConcurrentHashMap<>();
62 private static final Logger LOG = LoggerFactory.getLogger(HwvtepConnectionManager.class);
63 private static final String ENTITY_TYPE = "hwvtep";
65 private DataBroker db;
66 private TransactionInvoker txInvoker;
67 private Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers = new ConcurrentHashMap<>();
68 private Map<Entity, HwvtepConnectionInstance> entityConnectionMap = new ConcurrentHashMap<>();
69 private EntityOwnershipService entityOwnershipService;
70 private HwvtepDeviceEntityOwnershipListener hwvtepDeviceEntityOwnershipListener;
72 public HwvtepConnectionManager(DataBroker db, TransactionInvoker txInvoker,
73 EntityOwnershipService entityOwnershipService) {
75 this.txInvoker = txInvoker;
76 this.entityOwnershipService = entityOwnershipService;
77 this.hwvtepDeviceEntityOwnershipListener = new HwvtepDeviceEntityOwnershipListener(this,entityOwnershipService);
81 public void close() throws Exception {
82 if (hwvtepDeviceEntityOwnershipListener != null) {
83 hwvtepDeviceEntityOwnershipListener.close();
86 for (OvsdbClient client: clients.values()) {
92 public void connected(@Nonnull final OvsdbClient client) {
93 LOG.info("Library connected {} from {}:{} to {}:{}",
94 client.getConnectionInfo().getType(),
95 client.getConnectionInfo().getRemoteAddress(),
96 client.getConnectionInfo().getRemotePort(),
97 client.getConnectionInfo().getLocalAddress(),
98 client.getConnectionInfo().getLocalPort());
99 List<String> databases = new ArrayList<>();
101 databases = client.getDatabases().get();
102 } catch (InterruptedException | ExecutionException e) {
103 LOG.warn("Unable to fetch database list");
106 if(databases.contains(HwvtepSchemaConstants.HARDWARE_VTEP)) {
107 HwvtepConnectionInstance hwClient = connectedButCallBacksNotRegistered(client);
108 registerEntityForOwnership(hwClient);
113 public void disconnected(OvsdbClient client) {
114 LOG.info("Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
115 client.getConnectionInfo().getType(),
116 client.getConnectionInfo().getRemoteAddress(),
117 client.getConnectionInfo().getRemotePort(),
118 client.getConnectionInfo().getLocalAddress(),
119 client.getConnectionInfo().getLocalPort());
120 ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(client);
121 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
122 if (hwvtepConnectionInstance != null) {
123 //TODO: remove all the hwvtep nodes
124 txInvoker.invoke(new HwvtepGlobalRemoveCommand(hwvtepConnectionInstance, null, null));
125 removeConnectionInstance(key);
127 // Unregister Cluster Ownership for ConnectionInfo
128 unregisterEntityForOwnership(hwvtepConnectionInstance);
130 LOG.warn("HWVTEP disconnected event did not find connection instance for {}", key);
132 LOG.trace("HwvtepConnectionManager exit disconnected client: {}", client);
135 public OvsdbClient connect(InstanceIdentifier<Node> iid, HwvtepGlobalAugmentation hwvtepGlobal) throws UnknownHostException {
136 LOG.info("Connecting to {}", HwvtepSouthboundUtil.connectionInfoToString(hwvtepGlobal.getConnectionInfo()));
137 InetAddress ip = HwvtepSouthboundMapper.createInetAddress(hwvtepGlobal.getConnectionInfo().getRemoteIp());
138 OvsdbClient client = OvsdbConnectionService.getService()
139 .connect(ip, hwvtepGlobal.getConnectionInfo().getRemotePort().getValue());
141 putInstanceIdentifier(hwvtepGlobal.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
142 HwvtepConnectionInstance hwvtepConnectionInstance = connectedButCallBacksNotRegistered(client);
143 hwvtepConnectionInstance.setHwvtepGlobalAugmentation(hwvtepGlobal);
144 hwvtepConnectionInstance.setInstanceIdentifier(iid.firstIdentifierOf(Node.class));
146 // Register Cluster Ownership for ConnectionInfo
147 registerEntityForOwnership(hwvtepConnectionInstance);
149 LOG.warn("Failed to connect to OVSDB node: {}", hwvtepGlobal.getConnectionInfo());
153 public void disconnect(HwvtepGlobalAugmentation ovsdbNode) throws UnknownHostException {
154 LOG.info("Diconnecting from {}", HwvtepSouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
155 HwvtepConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
156 if (client != null) {
158 // Unregister Cluster Ownership for ConnectionInfo
159 unregisterEntityForOwnership(client);
160 removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
164 public HwvtepConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
165 LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
166 externalClient.getConnectionInfo().getRemotePort());
167 ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(externalClient);
168 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
170 // Check if existing hwvtepConnectionInstance for the OvsdbClient present.
171 // In such cases, we will see if the hwvtepConnectionInstance has same externalClient.
172 if (hwvtepConnectionInstance != null) {
173 if (hwvtepConnectionInstance.hasOvsdbClient(externalClient)) {
174 LOG.warn("HWVTEP Connection Instance {} already exists for client {}", key, externalClient);
175 return hwvtepConnectionInstance;
177 LOG.warn("HWVTEP Connection Instance {} being replaced with client {}", key, externalClient);
178 hwvtepConnectionInstance.disconnect();
180 // Unregister Cluster Ownership for ConnectionInfo
181 // Because the hwvtepConnectionInstance is about to be completely replaced!
182 unregisterEntityForOwnership(hwvtepConnectionInstance);
184 removeConnectionInstance(key);
187 hwvtepConnectionInstance = new HwvtepConnectionInstance(key, externalClient, getInstanceIdentifier(key),
189 hwvtepConnectionInstance.createTransactInvokers();
190 return hwvtepConnectionInstance;
193 private void putConnectionInstance(ConnectionInfo key,HwvtepConnectionInstance instance) {
194 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
195 clients.put(connectionInfo, instance);
196 LOG.info("Clients after put: {}", clients);
199 public HwvtepConnectionInstance getConnectionInstance(ConnectionInfo key) {
200 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
201 return clients.get(connectionInfo);
204 public HwvtepConnectionInstance getConnectionInstance(Node node) {
205 Preconditions.checkNotNull(node);
206 HwvtepGlobalAugmentation hwvtepGlobal = node.getAugmentation(HwvtepGlobalAugmentation.class);
207 PhysicalSwitchAugmentation pSwitchNode = node.getAugmentation(PhysicalSwitchAugmentation.class);
208 if (hwvtepGlobal != null) {
209 if(hwvtepGlobal.getConnectionInfo() != null) {
210 return getConnectionInstance(hwvtepGlobal.getConnectionInfo());
212 // TODO: Case of user configured connection
213 return null; //for now
215 } //TODO: We could get it from Managers also.
216 else if(pSwitchNode != null){
217 return getConnectionInstance(pSwitchNode);
219 LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
224 private HwvtepConnectionInstance getConnectionInstance(HwvtepPhysicalSwitchAttributes pNode) {
225 Optional<HwvtepGlobalAugmentation> optional = HwvtepSouthboundUtil.getManagingNode(db, pNode);
226 if(optional.isPresent()) {
227 return getConnectionInstance(optional.get().getConnectionInfo());
233 private void removeConnectionInstance(ConnectionInfo key) {
234 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
235 clients.remove(connectionInfo);
236 LOG.info("Clients after remove: {}", clients);
239 private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
240 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
241 instanceIdentifiers.put(connectionInfo, iid);
244 public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
245 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
246 return instanceIdentifiers.get(connectionInfo);
249 private void removeInstanceIdentifier(ConnectionInfo key) {
250 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
251 instanceIdentifiers.remove(connectionInfo);
254 public OvsdbClient getClient(ConnectionInfo connectionInfo) {
255 return getConnectionInstance(connectionInfo);
258 private void registerEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
260 Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
261 entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
262 hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
265 EntityOwnershipCandidateRegistration registration =
266 entityOwnershipService.registerCandidate(candidateEntity);
267 hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
268 LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
270 //If entity already has owner, it won't get notification from EntityOwnershipService
271 //so cache the connection instances.
272 Optional<EntityOwnershipState> ownershipStateOpt =
273 entityOwnershipService.getOwnershipState(candidateEntity);
274 if (ownershipStateOpt.isPresent()) {
275 EntityOwnershipState ownershipState = ownershipStateOpt.get();
276 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
277 if (getConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo()) != null) {
278 LOG.info("OVSDB entity {} is already owned by other southbound plugin "
279 + "instance, so *this* instance is NOT an OWNER of the device",
280 hwvtepConnectionInstance.getConnectionInfo());
281 putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
285 } catch (CandidateAlreadyRegisteredException e) {
286 LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
291 private Global getHwvtepGlobalTableEntry(HwvtepConnectionInstance connectionInstance) {
292 DatabaseSchema dbSchema = null;
293 Global globalRow = null;
296 dbSchema = connectionInstance.getSchema(HwvtepSchemaConstants.HARDWARE_VTEP).get();
297 } catch (InterruptedException | ExecutionException e) {
298 LOG.warn("Not able to fetch schema for database {} from device {}",
299 HwvtepSchemaConstants.HARDWARE_VTEP,connectionInstance.getConnectionInfo(),e);
302 if (dbSchema != null) {
303 GenericTableSchema hwvtepSchema = TyperUtils.getTableSchema(dbSchema, Global.class);
305 List<String> hwvtepTableColumn = new ArrayList<>();
306 hwvtepTableColumn.addAll(hwvtepSchema.getColumns());
307 Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
308 selectOperation.setColumns(hwvtepTableColumn);
310 ArrayList<Operation> operations = new ArrayList<>();
311 operations.add(selectOperation);
312 operations.add(op.comment("Fetching hardware_vtep table rows"));
315 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
316 if (results != null ) {
317 OperationResult selectResult = results.get(0);
318 globalRow = TyperUtils.getTypedRowWrapper(
319 dbSchema,Global.class,selectResult.getRows().get(0));
321 } catch (InterruptedException | ExecutionException e) {
322 LOG.warn("Not able to fetch hardware_vtep table row from device {}",
323 connectionInstance.getConnectionInfo(),e);
326 LOG.trace("Fetched global {} from hardware_vtep schema",globalRow);
330 private Entity getEntityFromConnectionInstance(@Nonnull HwvtepConnectionInstance hwvtepConnectionInstance) {
331 InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
333 //TODO: Is Global the right one?
334 Global hwvtepGlobalRow = getHwvtepGlobalTableEntry(hwvtepConnectionInstance);
335 iid = HwvtepSouthboundMapper.getInstanceIdentifier(hwvtepGlobalRow);
336 /* Let's set the iid now */
337 hwvtepConnectionInstance.setInstanceIdentifier(iid);
338 LOG.info("InstanceIdentifier {} generated for device "
339 + "connection {}",iid, hwvtepConnectionInstance.getConnectionInfo());
342 YangInstanceIdentifier entityId =
343 HwvtepSouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
344 Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
345 LOG.debug("Entity {} created for device connection {}",
346 deviceEntity, hwvtepConnectionInstance.getConnectionInfo());
349 private void unregisterEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
350 hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
351 entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
354 public void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
355 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
356 LOG.info("handleOwnershipChanged: {} event received for device {}",
357 ownershipChange, hwvtepConnectionInstance != null ? hwvtepConnectionInstance.getConnectionInfo()
358 : "THAT'S NOT REGISTERED BY THIS SOUTHBOUND PLUGIN INSTANCE");
360 if (hwvtepConnectionInstance == null) {
361 if (ownershipChange.isOwner()) {
362 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
364 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
365 // that instance registered for the device ownership or not. It is to make sure that
366 // If all the controller instance that was connected to the device are down, so the
367 // running instance can clear up the operational data store even though it was not
368 // connected to the device.
369 LOG.debug("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
372 // If entity has no owner, clean up the operational data store (it's possible because owner controller
373 // might went down abruptly and didn't get a chance to clean up the operational data store.
374 if (!ownershipChange.hasOwner()) {
375 LOG.debug("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
376 // Below code might look weird but it's required. We want to give first opportunity to the
377 // previous owner of the device to clean up the operational data store if there is no owner now.
378 // That way we will avoid lot of nasty md-sal exceptions because of concurrent delete.
379 if (ownershipChange.wasOwner()) {
380 cleanEntityOperationalData(ownershipChange.getEntity());
382 // If first cleanEntityOperationalData() was called, this call will be no-op.
383 cleanEntityOperationalData(ownershipChange.getEntity());
387 //Connection detail need to be cached, irrespective of ownership result.
388 putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
390 if (ownershipChange.isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
391 LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
392 hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
396 hwvtepConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
397 // You were not an owner, but now you are
398 if (ownershipChange.isOwner()) {
399 LOG.info("handleOwnershipChanged: *this* southbound plugin instance is owner of device {}",
400 hwvtepConnectionInstance.getConnectionInfo());
402 //*this* instance of southbound plugin is owner of the device,
403 //so register for monitor callbacks
404 hwvtepConnectionInstance.registerCallbacks();
407 //You were owner of the device, but now you are not. With the current ownership
408 //grant mechanism, this scenario should not occur. Because this scenario will occur
409 //when this controller went down or switch flap the connection, but in both the case
410 //it will go through the re-registration process. We need to implement this condition
411 //when clustering service implement a ownership grant strategy which can revoke the
412 //device ownership for load balancing the devices across the instances.
413 //Once this condition occur, we should unregister the callback.
414 LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}",
415 hwvtepConnectionInstance.getNodeId().getValue());
419 private void cleanEntityOperationalData(Entity entity) {
420 @SuppressWarnings("unchecked") final InstanceIdentifier<Node> nodeIid =
421 (InstanceIdentifier<Node>) HwvtepSouthboundUtil
422 .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
424 txInvoker.invoke(new TransactionCommand() {
426 public void execute(ReadWriteTransaction transaction) {
427 transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
432 private HwvtepConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
433 return entityConnectionMap.get(entity);
436 private class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
437 private HwvtepConnectionManager hcm;
438 private EntityOwnershipListenerRegistration listenerRegistration;
440 HwvtepDeviceEntityOwnershipListener(HwvtepConnectionManager hcm, EntityOwnershipService entityOwnershipService) {
442 listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
444 public void close() {
445 listenerRegistration.close();
448 public void ownershipChanged(EntityOwnershipChange ownershipChange) {
449 hcm.handleOwnershipChanged(ownershipChange);