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 HwvtepConnectionInstance hwClient = connectedButCallBacksNotRegistered(client);
100 registerEntityForOwnership(hwClient);
104 public void disconnected(OvsdbClient client) {
105 LOG.info("Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
106 client.getConnectionInfo().getType(),
107 client.getConnectionInfo().getRemoteAddress(),
108 client.getConnectionInfo().getRemotePort(),
109 client.getConnectionInfo().getLocalAddress(),
110 client.getConnectionInfo().getLocalPort());
111 ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(client);
112 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
113 if (hwvtepConnectionInstance != null) {
114 //TODO: remove all the hwvtep nodes
115 txInvoker.invoke(new HwvtepGlobalRemoveCommand(hwvtepConnectionInstance, null, null));
116 removeConnectionInstance(key);
118 // Unregister Cluster Ownership for ConnectionInfo
119 unregisterEntityForOwnership(hwvtepConnectionInstance);
121 LOG.warn("HWVTEP disconnected event did not find connection instance for {}", key);
123 LOG.trace("HwvtepConnectionManager exit disconnected client: {}", client);
126 public OvsdbClient connect(InstanceIdentifier<Node> iid, HwvtepGlobalAugmentation hwvtepGlobal) throws UnknownHostException {
127 LOG.info("Connecting to {}", HwvtepSouthboundUtil.connectionInfoToString(hwvtepGlobal.getConnectionInfo()));
128 InetAddress ip = HwvtepSouthboundMapper.createInetAddress(hwvtepGlobal.getConnectionInfo().getRemoteIp());
129 OvsdbClient client = OvsdbConnectionService.getService()
130 .connect(ip, hwvtepGlobal.getConnectionInfo().getRemotePort().getValue());
132 putInstanceIdentifier(hwvtepGlobal.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
133 HwvtepConnectionInstance hwvtepConnectionInstance = connectedButCallBacksNotRegistered(client);
134 hwvtepConnectionInstance.setHwvtepGlobalAugmentation(hwvtepGlobal);
135 hwvtepConnectionInstance.setInstanceIdentifier(iid.firstIdentifierOf(Node.class));
137 // Register Cluster Ownership for ConnectionInfo
138 registerEntityForOwnership(hwvtepConnectionInstance);
140 LOG.warn("Failed to connect to OVSDB node: {}", hwvtepGlobal.getConnectionInfo());
144 public void disconnect(HwvtepGlobalAugmentation ovsdbNode) throws UnknownHostException {
145 LOG.info("Diconnecting from {}", HwvtepSouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
146 HwvtepConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
147 if (client != null) {
149 // Unregister Cluster Ownership for ConnectionInfo
150 unregisterEntityForOwnership(client);
151 removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
155 public HwvtepConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
156 LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
157 externalClient.getConnectionInfo().getRemotePort());
158 ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(externalClient);
159 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
161 // Check if existing hwvtepConnectionInstance for the OvsdbClient present.
162 // In such cases, we will see if the hwvtepConnectionInstance has same externalClient.
163 if (hwvtepConnectionInstance != null) {
164 if (hwvtepConnectionInstance.hasOvsdbClient(externalClient)) {
165 LOG.warn("HWVTEP Connection Instance {} already exists for client {}", key, externalClient);
166 return hwvtepConnectionInstance;
168 LOG.warn("HWVTEP Connection Instance {} being replaced with client {}", key, externalClient);
169 hwvtepConnectionInstance.disconnect();
171 // Unregister Cluster Ownership for ConnectionInfo
172 // Because the hwvtepConnectionInstance is about to be completely replaced!
173 unregisterEntityForOwnership(hwvtepConnectionInstance);
175 removeConnectionInstance(key);
178 hwvtepConnectionInstance = new HwvtepConnectionInstance(key, externalClient, getInstanceIdentifier(key),
180 hwvtepConnectionInstance.createTransactInvokers();
181 return hwvtepConnectionInstance;
184 private void putConnectionInstance(ConnectionInfo key,HwvtepConnectionInstance instance) {
185 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
186 clients.put(connectionInfo, instance);
187 LOG.info("Clients after put: {}", clients);
190 public HwvtepConnectionInstance getConnectionInstance(ConnectionInfo key) {
191 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
192 return clients.get(connectionInfo);
195 public HwvtepConnectionInstance getConnectionInstance(Node node) {
196 Preconditions.checkNotNull(node);
197 HwvtepGlobalAugmentation hwvtepGlobal = node.getAugmentation(HwvtepGlobalAugmentation.class);
198 PhysicalSwitchAugmentation pSwitchNode = node.getAugmentation(PhysicalSwitchAugmentation.class);
199 if (hwvtepGlobal != null) {
200 if(hwvtepGlobal.getConnectionInfo() != null) {
201 return getConnectionInstance(hwvtepGlobal.getConnectionInfo());
203 // TODO: Case of user configured connection
204 return null; //for now
206 } //TODO: We could get it from Managers also.
207 else if(pSwitchNode != null){
208 return getConnectionInstance(pSwitchNode);
210 LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
215 private HwvtepConnectionInstance getConnectionInstance(HwvtepPhysicalSwitchAttributes pNode) {
216 Optional<HwvtepGlobalAugmentation> optional = HwvtepSouthboundUtil.getManagingNode(db, pNode);
217 if(optional.isPresent()) {
218 return getConnectionInstance(optional.get().getConnectionInfo());
224 private void removeConnectionInstance(ConnectionInfo key) {
225 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
226 clients.remove(connectionInfo);
227 LOG.info("Clients after remove: {}", clients);
230 private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
231 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
232 instanceIdentifiers.put(connectionInfo, iid);
235 public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
236 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
237 return instanceIdentifiers.get(connectionInfo);
240 private void removeInstanceIdentifier(ConnectionInfo key) {
241 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
242 instanceIdentifiers.remove(connectionInfo);
245 public OvsdbClient getClient(ConnectionInfo connectionInfo) {
246 return getConnectionInstance(connectionInfo);
249 private void registerEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
251 Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
252 entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
253 hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
256 EntityOwnershipCandidateRegistration registration =
257 entityOwnershipService.registerCandidate(candidateEntity);
258 hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
259 LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
261 //If entity already has owner, it won't get notification from EntityOwnershipService
262 //so cache the connection instances.
263 Optional<EntityOwnershipState> ownershipStateOpt =
264 entityOwnershipService.getOwnershipState(candidateEntity);
265 if (ownershipStateOpt.isPresent()) {
266 EntityOwnershipState ownershipState = ownershipStateOpt.get();
267 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
268 if (getConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo()) != null) {
269 LOG.info("OVSDB entity {} is already owned by other southbound plugin "
270 + "instance, so *this* instance is NOT an OWNER of the device",
271 hwvtepConnectionInstance.getConnectionInfo());
272 putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
276 } catch (CandidateAlreadyRegisteredException e) {
277 LOG.warn("OVSDB entity {} was already registered for {} ownership", candidateEntity, e);
282 private Global getHwvtepGlobalTableEntry(HwvtepConnectionInstance connectionInstance) {
283 DatabaseSchema dbSchema = null;
284 Global globalRow = null;
287 dbSchema = connectionInstance.getSchema(HwvtepSchemaConstants.HARDWARE_VTEP).get();
288 } catch (InterruptedException | ExecutionException e) {
289 LOG.warn("Not able to fetch schema for database {} from device {}",
290 HwvtepSchemaConstants.HARDWARE_VTEP,connectionInstance.getConnectionInfo(),e);
293 if (dbSchema != null) {
294 GenericTableSchema hwvtepSchema = TyperUtils.getTableSchema(dbSchema, Global.class);
296 List<String> hwvtepTableColumn = new ArrayList<>();
297 hwvtepTableColumn.addAll(hwvtepSchema.getColumns());
298 Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
299 selectOperation.setColumns(hwvtepTableColumn);
301 ArrayList<Operation> operations = new ArrayList<>();
302 operations.add(selectOperation);
303 operations.add(op.comment("Fetching hardware_vtep table rows"));
306 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
307 if (results != null ) {
308 OperationResult selectResult = results.get(0);
309 globalRow = TyperUtils.getTypedRowWrapper(
310 dbSchema,Global.class,selectResult.getRows().get(0));
312 } catch (InterruptedException | ExecutionException e) {
313 LOG.warn("Not able to fetch hardware_vtep table row from device {}",
314 connectionInstance.getConnectionInfo(),e);
317 LOG.trace("Fetched global {} from hardware_vtep schema",globalRow);
321 private Entity getEntityFromConnectionInstance(@Nonnull HwvtepConnectionInstance hwvtepConnectionInstance) {
322 InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
324 //TODO: Is Global the right one?
325 Global hwvtepGlobalRow = getHwvtepGlobalTableEntry(hwvtepConnectionInstance);
326 iid = HwvtepSouthboundMapper.getInstanceIdentifier(hwvtepGlobalRow);
327 /* Let's set the iid now */
328 hwvtepConnectionInstance.setInstanceIdentifier(iid);
329 LOG.info("InstanceIdentifier {} generated for device "
330 + "connection {}",iid, hwvtepConnectionInstance.getConnectionInfo());
333 YangInstanceIdentifier entityId =
334 HwvtepSouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
335 Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
336 LOG.debug("Entity {} created for device connection {}",
337 deviceEntity, hwvtepConnectionInstance.getConnectionInfo());
340 private void unregisterEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
341 hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
342 entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
345 public void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
346 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
347 LOG.info("handleOwnershipChanged: {} event received for device {}",
348 ownershipChange, hwvtepConnectionInstance != null ? hwvtepConnectionInstance.getConnectionInfo()
349 : "THAT'S NOT REGISTERED BY THIS SOUTHBOUND PLUGIN INSTANCE");
351 if (hwvtepConnectionInstance == null) {
352 if (ownershipChange.isOwner()) {
353 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
355 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
356 // that instance registered for the device ownership or not. It is to make sure that
357 // If all the controller instance that was connected to the device are down, so the
358 // running instance can clear up the operational data store even though it was not
359 // connected to the device.
360 LOG.debug("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
363 // If entity has no owner, clean up the operational data store (it's possible because owner controller
364 // might went down abruptly and didn't get a chance to clean up the operational data store.
365 if (!ownershipChange.hasOwner()) {
366 LOG.debug("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
367 // Below code might look weird but it's required. We want to give first opportunity to the
368 // previous owner of the device to clean up the operational data store if there is no owner now.
369 // That way we will avoid lot of nasty md-sal exceptions because of concurrent delete.
370 if (ownershipChange.wasOwner()) {
371 cleanEntityOperationalData(ownershipChange.getEntity());
373 // If first cleanEntityOperationalData() was called, this call will be no-op.
374 cleanEntityOperationalData(ownershipChange.getEntity());
378 //Connection detail need to be cached, irrespective of ownership result.
379 putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
381 if (ownershipChange.isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
382 LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
383 hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
387 hwvtepConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
388 // You were not an owner, but now you are
389 if (ownershipChange.isOwner()) {
390 LOG.info("handleOwnershipChanged: *this* southbound plugin instance is owner of device {}",
391 hwvtepConnectionInstance.getConnectionInfo());
393 //*this* instance of southbound plugin is owner of the device,
394 //so register for monitor callbacks
395 hwvtepConnectionInstance.registerCallbacks();
398 //You were owner of the device, but now you are not. With the current ownership
399 //grant mechanism, this scenario should not occur. Because this scenario will occur
400 //when this controller went down or switch flap the connection, but in both the case
401 //it will go through the re-registration process. We need to implement this condition
402 //when clustering service implement a ownership grant strategy which can revoke the
403 //device ownership for load balancing the devices across the instances.
404 //Once this condition occur, we should unregister the callback.
405 LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}",
406 hwvtepConnectionInstance.getNodeId().getValue());
410 private void cleanEntityOperationalData(Entity entity) {
411 @SuppressWarnings("unchecked") final InstanceIdentifier<Node> nodeIid =
412 (InstanceIdentifier<Node>) HwvtepSouthboundUtil
413 .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
415 txInvoker.invoke(new TransactionCommand() {
417 public void execute(ReadWriteTransaction transaction) {
418 transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
423 private HwvtepConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
424 return entityConnectionMap.get(entity);
427 private class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
428 private HwvtepConnectionManager hcm;
429 private EntityOwnershipListenerRegistration listenerRegistration;
431 HwvtepDeviceEntityOwnershipListener(HwvtepConnectionManager hcm, EntityOwnershipService entityOwnershipService) {
433 listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
435 public void close() {
436 listenerRegistration.close();
439 public void ownershipChanged(EntityOwnershipChange ownershipChange) {
440 hcm.handleOwnershipChanged(ownershipChange);