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.ovsdb.hwvtepsouthbound.transactions.md.HwvtepGlobalRemoveCommand;
34 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.PhysicalSwitchRemoveCommand;
35 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvoker;
36 import org.opendaylight.ovsdb.lib.OvsdbClient;
37 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
38 import org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService;
39 import org.opendaylight.ovsdb.lib.operations.Operation;
40 import org.opendaylight.ovsdb.lib.operations.OperationResult;
41 import org.opendaylight.ovsdb.lib.operations.Select;
42 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
43 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
44 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
45 import org.opendaylight.ovsdb.schema.hardwarevtep.Global;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ConnectionInfo;
48 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
49 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 import com.google.common.base.Optional;
55 import com.google.common.base.Preconditions;
57 public class HwvtepConnectionManager implements OvsdbConnectionListener, AutoCloseable{
58 private Map<ConnectionInfo, HwvtepConnectionInstance> clients =
59 new ConcurrentHashMap<ConnectionInfo,HwvtepConnectionInstance>();
60 private static final Logger LOG = LoggerFactory.getLogger(HwvtepConnectionManager.class);
61 private static final String ENTITY_TYPE = "hwvtep";
63 private DataBroker db;
64 private TransactionInvoker txInvoker;
65 private Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
66 new ConcurrentHashMap<ConnectionInfo,InstanceIdentifier<Node>>();
67 private Map<Entity, HwvtepConnectionInstance> entityConnectionMap =
68 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 HwvtepConnectionInstance hwClient = connectedButCallBacksNotRegistered(client);
94 registerEntityForOwnership(hwClient);
95 LOG.trace("connected client: {}", client);
99 public void disconnected(OvsdbClient client) {
100 LOG.info("HWVTEP Disconnected from {}:{}. Cleaning up the operational data store"
101 ,client.getConnectionInfo().getRemoteAddress(),
102 client.getConnectionInfo().getRemotePort());
103 ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(client);
104 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
105 if (hwvtepConnectionInstance != null) {
106 //TODO: remove all the hwvtep nodes
107 txInvoker.invoke(new HwvtepGlobalRemoveCommand(hwvtepConnectionInstance, null, null));
108 removeConnectionInstance(key);
110 // Unregister Cluster Ownership for ConnectionInfo
111 unregisterEntityForOwnership(hwvtepConnectionInstance);
113 LOG.warn("HWVTEP disconnected event did not find connection instance for {}", key);
115 LOG.trace("disconnected client: {}", client);
118 public OvsdbClient connect(InstanceIdentifier<Node> iid, HwvtepGlobalAugmentation hwvtepGlobal) throws UnknownHostException {
119 InetAddress ip = HwvtepSouthboundMapper.createInetAddress(hwvtepGlobal.getConnectionInfo().getRemoteIp());
120 OvsdbClient client = OvsdbConnectionService.getService()
121 .connect(ip, hwvtepGlobal.getConnectionInfo().getRemotePort().getValue());
123 putInstanceIdentifier(hwvtepGlobal.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
124 HwvtepConnectionInstance hwvtepConnectionInstance = connectedButCallBacksNotRegistered(client);
125 hwvtepConnectionInstance.setHwvtepGlobalAugmentation(hwvtepGlobal);
126 hwvtepConnectionInstance.setInstanceIdentifier(iid.firstIdentifierOf(Node.class));
128 // Register Cluster Ownership for ConnectionInfo
129 registerEntityForOwnership(hwvtepConnectionInstance);
131 LOG.warn("Failed to connect to OVSDB node: {}", hwvtepGlobal.getConnectionInfo());
135 public void disconnect(HwvtepGlobalAugmentation ovsdbNode) throws UnknownHostException {
136 HwvtepConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
137 if (client != null) {
139 // Unregister Cluster Ownership for ConnectionInfo
140 unregisterEntityForOwnership(client);
141 removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
145 public HwvtepConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
146 LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
147 externalClient.getConnectionInfo().getRemotePort());
148 ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(externalClient);
149 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
151 // Check if existing hwvtepConnectionInstance for the OvsdbClient present.
152 // In such cases, we will see if the hwvtepConnectionInstance has same externalClient.
153 if (hwvtepConnectionInstance != null) {
154 if (hwvtepConnectionInstance.hasOvsdbClient(externalClient)) {
155 LOG.warn("HWVTEP Connection Instance {} already exists for client {}", key, externalClient);
156 return hwvtepConnectionInstance;
158 LOG.warn("HWVTEP Connection Instance {} being replaced with client {}", key, externalClient);
159 hwvtepConnectionInstance.disconnect();
161 // Unregister Cluster Ownership for ConnectionInfo
162 // Because the hwvtepConnectionInstance is about to be completely replaced!
163 unregisterEntityForOwnership(hwvtepConnectionInstance);
165 removeConnectionInstance(key);
168 hwvtepConnectionInstance = new HwvtepConnectionInstance(key, externalClient, getInstanceIdentifier(key),
170 hwvtepConnectionInstance.createTransactInvokers();
171 return hwvtepConnectionInstance;
174 private void putConnectionInstance(ConnectionInfo key,HwvtepConnectionInstance instance) {
175 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
176 clients.put(connectionInfo, instance);
177 LOG.info("Clients after put: {}", clients);
180 public HwvtepConnectionInstance getConnectionInstance(ConnectionInfo key) {
181 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
182 return clients.get(connectionInfo);
184 public HwvtepConnectionInstance getConnectionInstance(Node node) {
185 Preconditions.checkNotNull(node);
186 HwvtepGlobalAugmentation hwvtepGlobal = node.getAugmentation(HwvtepGlobalAugmentation.class);
187 if (hwvtepGlobal != null) {
188 return getConnectionInstance(hwvtepGlobal.getConnectionInfo());
189 } //TODO: We could get it from Managers also.
191 LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
196 private void removeConnectionInstance(ConnectionInfo key) {
197 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
198 clients.remove(connectionInfo);
199 LOG.info("Clients after remove: {}", clients);
202 private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
203 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
204 instanceIdentifiers.put(connectionInfo, iid);
207 public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
208 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
209 InstanceIdentifier<Node> iid = instanceIdentifiers.get(connectionInfo);
213 private void removeInstanceIdentifier(ConnectionInfo key) {
214 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
215 instanceIdentifiers.remove(connectionInfo);
218 public OvsdbClient getClient(ConnectionInfo connectionInfo) {
219 return getConnectionInstance(connectionInfo);
222 private void registerEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
224 Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
225 entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
226 hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
229 EntityOwnershipCandidateRegistration registration =
230 entityOwnershipService.registerCandidate(candidateEntity);
231 hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
232 LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
234 //If entity already has owner, it won't get notification from EntityOwnershipService
235 //so cache the connection instances.
236 Optional<EntityOwnershipState> ownershipStateOpt =
237 entityOwnershipService.getOwnershipState(candidateEntity);
238 if (ownershipStateOpt.isPresent()) {
239 EntityOwnershipState ownershipState = ownershipStateOpt.get();
240 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
241 if (getConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo()) != null) {
242 LOG.info("OVSDB entity {} is already owned by other southbound plugin "
243 + "instance, so *this* instance is NOT an OWNER of the device",
244 hwvtepConnectionInstance.getConnectionInfo());
245 putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
249 } catch (CandidateAlreadyRegisteredException e) {
250 LOG.warn("OVSDB entity {} was already registered for {} ownership", candidateEntity, e);
255 private Global getHwvtepGlobalTableEntry(HwvtepConnectionInstance connectionInstance) {
256 DatabaseSchema dbSchema = null;
257 Global globalRow = null;
260 dbSchema = connectionInstance.getSchema(HwvtepSchemaConstants.databaseName).get();
261 } catch (InterruptedException | ExecutionException e) {
262 LOG.warn("Not able to fetch schema for database {} from device {}",
263 HwvtepSchemaConstants.databaseName,connectionInstance.getConnectionInfo(),e);
266 if (dbSchema != null) {
267 GenericTableSchema hwvtepSchema = TyperUtils.getTableSchema(dbSchema, Global.class);
269 List<String> hwvtepTableColumn = new ArrayList<String>();
270 hwvtepTableColumn.addAll(hwvtepSchema.getColumns());
271 Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
272 selectOperation.setColumns(hwvtepTableColumn);;
274 ArrayList<Operation> operations = new ArrayList<Operation>();
275 operations.add(selectOperation);
276 operations.add(op.comment("Fetching hardware_vtep table rows"));
278 List<OperationResult> results = null;
280 results = connectionInstance.transact(dbSchema, operations).get();
281 if (results != null ) {
282 OperationResult selectResult = results.get(0);
283 globalRow = TyperUtils.getTypedRowWrapper(
284 dbSchema,Global.class,selectResult.getRows().get(0));
286 } catch (InterruptedException | ExecutionException e) {
287 LOG.warn("Not able to fetch hardware_vtep table row from device {}",
288 connectionInstance.getConnectionInfo(),e);
291 LOG.trace("Fetched global {} from hardware_vtep schema",globalRow);
295 private Entity getEntityFromConnectionInstance(@Nonnull HwvtepConnectionInstance hwvtepConnectionInstance) {
296 YangInstanceIdentifier entityId = null;
297 InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
299 //TODO: Is Global the right one?
300 Global hwvtepGlobalRow = getHwvtepGlobalTableEntry(hwvtepConnectionInstance);
301 iid = HwvtepSouthboundMapper.getInstanceIdentifier(hwvtepGlobalRow);
302 /* Let's set the iid now */
303 hwvtepConnectionInstance.setInstanceIdentifier(iid);
304 LOG.info("InstanceIdentifier {} generated for device "
305 + "connection {}",iid, hwvtepConnectionInstance.getConnectionInfo());
308 entityId = HwvtepSouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
309 Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
310 LOG.debug("Entity {} created for device connection {}",
311 deviceEntity, hwvtepConnectionInstance.getConnectionInfo());
314 private void unregisterEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
315 hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
316 entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
319 public void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
320 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
321 LOG.info("handleOwnershipChanged: {} event received for device {}",
322 ownershipChange, hwvtepConnectionInstance != null ? hwvtepConnectionInstance.getConnectionInfo()
323 : "THAT'S NOT REGISTERED BY THIS SOUTHBOUND PLUGIN INSTANCE");
325 if (hwvtepConnectionInstance == null) {
326 if (ownershipChange.isOwner()) {
327 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
329 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
330 // that instance registered for the device ownership or not. It is to make sure that
331 // If all the controller instance that was connected to the device are down, so the
332 // running instance can clear up the operational data store even though it was not
333 // connected to the device.
334 LOG.debug("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
337 // If entity has no owner, clean up the operational data store (it's possible because owner controller
338 // might went down abruptly and didn't get a chance to clean up the operational data store.
339 if (!ownershipChange.hasOwner()) {
340 LOG.debug("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
341 // Below code might look weird but it's required. We want to give first opportunity to the
342 // previous owner of the device to clean up the operational data store if there is no owner now.
343 // That way we will avoid lot of nasty md-sal exceptions because of concurrent delete.
344 if (ownershipChange.wasOwner()) {
345 cleanEntityOperationalData(ownershipChange.getEntity());
347 // If first cleanEntityOperationalData() was called, this call will be no-op.
348 cleanEntityOperationalData(ownershipChange.getEntity());
352 //Connection detail need to be cached, irrespective of ownership result.
353 putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
355 if (ownershipChange.isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
356 LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
357 hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
361 hwvtepConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
362 // You were not an owner, but now you are
363 if (ownershipChange.isOwner()) {
364 LOG.info("handleOwnershipChanged: *this* southbound plugin instance is owner of device {}",
365 hwvtepConnectionInstance.getConnectionInfo());
367 //*this* instance of southbound plugin is owner of the device,
368 //so register for monitor callbacks
369 hwvtepConnectionInstance.registerCallbacks();
372 //You were owner of the device, but now you are not. With the current ownership
373 //grant mechanism, this scenario should not occur. Because this scenario will occur
374 //when this controller went down or switch flap the connection, but in both the case
375 //it will go through the re-registration process. We need to implement this condition
376 //when clustering service implement a ownership grant strategy which can revoke the
377 //device ownership for load balancing the devices across the instances.
378 //Once this condition occur, we should unregister the callback.
379 LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}",
380 hwvtepConnectionInstance.getNodeId().getValue());
384 private void cleanEntityOperationalData(Entity entity) {
385 InstanceIdentifier<Node> nodeIid = (InstanceIdentifier<Node>) HwvtepSouthboundUtil
386 .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
388 final ReadWriteTransaction transaction = db.newReadWriteTransaction();
389 Optional<Node> node = HwvtepSouthboundUtil.readNode(transaction, nodeIid);
390 if (node.isPresent()) {
391 HwvtepSouthboundUtil.deleteNode(transaction, nodeIid);
395 private HwvtepConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
396 return entityConnectionMap.get(entity);
399 private class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
400 private HwvtepConnectionManager hcm;
401 private EntityOwnershipListenerRegistration listenerRegistration;
403 HwvtepDeviceEntityOwnershipListener(HwvtepConnectionManager hcm, EntityOwnershipService entityOwnershipService) {
405 listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
407 public void close() {
408 listenerRegistration.close();
411 public void ownershipChanged(EntityOwnershipChange ownershipChange) {
412 hcm.handleOwnershipChanged(ownershipChange);