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.common.api.clustering.CandidateAlreadyRegisteredException;
25 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
26 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
27 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
28 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
29 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
30 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
31 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
32 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvoker;
33 import org.opendaylight.ovsdb.lib.OvsdbClient;
34 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
35 import org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService;
36 import org.opendaylight.ovsdb.lib.operations.Operation;
37 import org.opendaylight.ovsdb.lib.operations.OperationResult;
38 import org.opendaylight.ovsdb.lib.operations.Select;
39 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
40 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
41 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
42 import org.opendaylight.ovsdb.schema.hardwarevtep.Global;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ConnectionInfo;
45 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
46 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 import com.google.common.base.Optional;
53 public class HwvtepConnectionManager implements OvsdbConnectionListener, AutoCloseable{
54 private Map<ConnectionInfo, HwvtepConnectionInstance> clients =
55 new ConcurrentHashMap<ConnectionInfo,HwvtepConnectionInstance>();
56 private static final Logger LOG = LoggerFactory.getLogger(HwvtepConnectionManager.class);
57 private static final String ENTITY_TYPE = "hwvtep";
59 private DataBroker db;
60 private TransactionInvoker txInvoker;
61 private Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
62 new ConcurrentHashMap<ConnectionInfo,InstanceIdentifier<Node>>();
63 private Map<Entity, HwvtepConnectionInstance> entityConnectionMap =
64 new ConcurrentHashMap<>();
65 private EntityOwnershipService entityOwnershipService;
66 private HwvtepDeviceEntityOwnershipListener hwvtepDeviceEntityOwnershipListener;
68 public HwvtepConnectionManager(DataBroker db, TransactionInvoker txInvoker,
69 EntityOwnershipService entityOwnershipService) {
71 this.txInvoker = txInvoker;
72 this.entityOwnershipService = entityOwnershipService;
73 this.hwvtepDeviceEntityOwnershipListener = new HwvtepDeviceEntityOwnershipListener(this,entityOwnershipService);
77 public void close() throws Exception {
78 if (hwvtepDeviceEntityOwnershipListener != null) {
79 hwvtepDeviceEntityOwnershipListener.close();
82 for (OvsdbClient client: clients.values()) {
88 public void connected(@Nonnull final OvsdbClient client) {
89 HwvtepConnectionInstance hwClient = connectedButCallBacksNotRegistered(client);
90 registerEntityForOwnership(hwClient);
91 LOG.trace("connected client: {}", client);
95 public void disconnected(OvsdbClient client) {
96 LOG.info("HWVTEP Disconnected from {}:{}. Cleaning up the operational data store"
97 ,client.getConnectionInfo().getRemoteAddress(),
98 client.getConnectionInfo().getRemotePort());
99 ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(client);
100 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
101 if (hwvtepConnectionInstance != null) {
102 //TODO: txInvoker.invoke(new HwvtepNodeRemoveCommand(hwvtepConnectionInstance, null, null));
103 removeConnectionInstance(key);
105 // Unregister Cluster Ownership for ConnectionInfo
106 unregisterEntityForOwnership(hwvtepConnectionInstance);
108 LOG.warn("HWVTEP disconnected event did not find connection instance for {}", key);
110 LOG.trace("disconnected client: {}", client);
113 public OvsdbClient connect(InstanceIdentifier<Node> iid, HwvtepGlobalAugmentation hwvtepGlobal) throws UnknownHostException {
114 InetAddress ip = HwvtepSouthboundMapper.createInetAddress(hwvtepGlobal.getConnectionInfo().getRemoteIp());
115 OvsdbClient client = OvsdbConnectionService.getService()
116 .connect(ip, hwvtepGlobal.getConnectionInfo().getRemotePort().getValue());
118 putInstanceIdentifier(hwvtepGlobal.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
119 HwvtepConnectionInstance hwvtepConnectionInstance = connectedButCallBacksNotRegistered(client);
120 hwvtepConnectionInstance.setHwvtepGlobalAugmentation(hwvtepGlobal);
122 // Register Cluster Ownership for ConnectionInfo
123 registerEntityForOwnership(hwvtepConnectionInstance);
125 LOG.warn("Failed to connect to OVSDB node: {}", hwvtepGlobal.getConnectionInfo());
129 public void disconnect(HwvtepGlobalAugmentation ovsdbNode) throws UnknownHostException {
130 HwvtepConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
131 if (client != null) {
133 // Unregister Cluster Ownership for ConnectionInfo
134 unregisterEntityForOwnership(client);
135 removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
139 public HwvtepConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
140 LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
141 externalClient.getConnectionInfo().getRemotePort());
142 ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(externalClient);
143 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
145 // Check if existing hwvtepConnectionInstance for the OvsdbClient present.
146 // In such cases, we will see if the hwvtepConnectionInstance has same externalClient.
147 if (hwvtepConnectionInstance != null) {
148 if (hwvtepConnectionInstance.hasOvsdbClient(externalClient)) {
149 LOG.warn("HWVTEP Connection Instance {} already exists for client {}", key, externalClient);
150 return hwvtepConnectionInstance;
152 LOG.warn("HWVTEP Connection Instance {} being replaced with client {}", key, externalClient);
153 hwvtepConnectionInstance.disconnect();
155 // Unregister Cluster Ownership for ConnectionInfo
156 // Because the hwvtepConnectionInstance is about to be completely replaced!
157 unregisterEntityForOwnership(hwvtepConnectionInstance);
159 removeConnectionInstance(key);
162 hwvtepConnectionInstance = new HwvtepConnectionInstance(key, externalClient, getInstanceIdentifier(key),
164 hwvtepConnectionInstance.createTransactInvokers();
165 return hwvtepConnectionInstance;
169 public OvsdbClient connect(InstanceIdentifier<Node> iid, OvsdbNodeAugmentation ovsdbNode)
170 throws UnknownHostException {
173 public void disconnect(OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
174 OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
180 private void putConnectionInstance(ConnectionInfo key,HwvtepConnectionInstance instance) {
181 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
182 clients.put(connectionInfo, instance);
183 LOG.info("Clients after put: {}", clients);
186 public HwvtepConnectionInstance getConnectionInstance(ConnectionInfo key) {
187 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
188 return clients.get(connectionInfo);
191 private void removeConnectionInstance(ConnectionInfo key) {
192 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
193 clients.remove(connectionInfo);
194 LOG.info("Clients after remove: {}", clients);
197 private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
198 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
199 instanceIdentifiers.put(connectionInfo, iid);
202 public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
203 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
204 InstanceIdentifier<Node> iid = instanceIdentifiers.get(connectionInfo);
208 private void removeInstanceIdentifier(ConnectionInfo key) {
209 ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
210 instanceIdentifiers.remove(connectionInfo);
213 public OvsdbClient getClient(ConnectionInfo connectionInfo) {
214 return getConnectionInstance(connectionInfo);
217 private void registerEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
219 Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
220 entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
221 hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
224 EntityOwnershipCandidateRegistration registration =
225 entityOwnershipService.registerCandidate(candidateEntity);
226 hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
227 LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
229 //If entity already has owner, it won't get notification from EntityOwnershipService
230 //so cache the connection instances.
231 Optional<EntityOwnershipState> ownershipStateOpt =
232 entityOwnershipService.getOwnershipState(candidateEntity);
233 if (ownershipStateOpt.isPresent()) {
234 EntityOwnershipState ownershipState = ownershipStateOpt.get();
235 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
236 if (getConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo()) != null) {
237 LOG.info("OVSDB entity {} is already owned by other southbound plugin "
238 + "instance, so *this* instance is NOT an OWNER of the device",
239 hwvtepConnectionInstance.getConnectionInfo());
240 putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
244 } catch (CandidateAlreadyRegisteredException e) {
245 LOG.warn("OVSDB entity {} was already registered for {} ownership", candidateEntity, e);
250 private Global getHwvtepGlobalTableEntry(HwvtepConnectionInstance connectionInstance) {
251 DatabaseSchema dbSchema = null;
252 Global globalRow = null;
255 dbSchema = connectionInstance.getSchema(HwvtepSchemaConstants.databaseName).get();
256 } catch (InterruptedException | ExecutionException e) {
257 LOG.warn("Not able to fetch schema for database {} from device {}",
258 HwvtepSchemaConstants.databaseName,connectionInstance.getConnectionInfo(),e);
261 if (dbSchema != null) {
262 GenericTableSchema hwvtepSchema = TyperUtils.getTableSchema(dbSchema, Global.class);
264 List<String> hwvtepTableColumn = new ArrayList<String>();
265 hwvtepTableColumn.addAll(hwvtepSchema.getColumns());
266 Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
267 selectOperation.setColumns(hwvtepTableColumn);;
269 ArrayList<Operation> operations = new ArrayList<Operation>();
270 operations.add(selectOperation);
271 operations.add(op.comment("Fetching hardware_vtep table rows"));
273 List<OperationResult> results = null;
275 results = connectionInstance.transact(dbSchema, operations).get();
276 if (results != null ) {
277 OperationResult selectResult = results.get(0);
278 globalRow = TyperUtils.getTypedRowWrapper(
279 dbSchema,Global.class,selectResult.getRows().get(0));
281 } catch (InterruptedException | ExecutionException e) {
282 LOG.warn("Not able to fetch hardware_vtep table row from device {}",
283 connectionInstance.getConnectionInfo(),e);
286 LOG.trace("Fetched global {} from hardware_vtep schema",globalRow);
290 private Entity getEntityFromConnectionInstance(@Nonnull HwvtepConnectionInstance hwvtepConnectionInstance) {
291 YangInstanceIdentifier entityId = null;
292 InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
294 //TODO: Is Global the right one?
295 Global hwvtepGlobalRow = getHwvtepGlobalTableEntry(hwvtepConnectionInstance);
296 iid = HwvtepSouthboundMapper.getInstanceIdentifier(hwvtepGlobalRow);
297 LOG.info("InstanceIdentifier {} generated for device "
298 + "connection {}",iid, hwvtepConnectionInstance.getConnectionInfo());
301 entityId = HwvtepSouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
302 Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
303 LOG.debug("Entity {} created for device connection {}",
304 deviceEntity, hwvtepConnectionInstance.getConnectionInfo());
307 private void unregisterEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
308 hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
309 entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
312 public void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
313 HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
314 LOG.info("handleOwnershipChanged: {} event received for device {}",
315 ownershipChange, hwvtepConnectionInstance != null ? hwvtepConnectionInstance.getConnectionInfo()
316 : "THAT'S NOT REGISTERED BY THIS SOUTHBOUND PLUGIN INSTANCE");
318 if (hwvtepConnectionInstance == null) {
319 if (ownershipChange.isOwner()) {
320 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
322 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
323 // that instance registered for the device ownership or not. It is to make sure that
324 // If all the controller instance that was connected to the device are down, so the
325 // running instance can clear up the operational data store even though it was not
326 // connected to the device.
327 LOG.debug("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
330 // If entity has no owner, clean up the operational data store (it's possible because owner controller
331 // might went down abruptly and didn't get a chance to clean up the operational data store.
332 if (!ownershipChange.hasOwner()) {
333 LOG.debug("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
334 // Below code might look weird but it's required. We want to give first opportunity to the
335 // previous owner of the device to clean up the operational data store if there is no owner now.
336 // That way we will avoid lot of nasty md-sal exceptions because of concurrent delete.
337 if (ownershipChange.wasOwner()) {
338 cleanEntityOperationalData(ownershipChange.getEntity());
340 // If first cleanEntityOperationalData() was called, this call will be no-op.
341 cleanEntityOperationalData(ownershipChange.getEntity());
345 //Connection detail need to be cached, irrespective of ownership result.
346 putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
348 if (ownershipChange.isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
349 LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
350 hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
354 hwvtepConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
355 // You were not an owner, but now you are
356 if (ownershipChange.isOwner()) {
357 LOG.info("handleOwnershipChanged: *this* southbound plugin instance is owner of device {}",
358 hwvtepConnectionInstance.getConnectionInfo());
360 //*this* instance of southbound plugin is owner of the device,
361 //so register for monitor callbacks
362 hwvtepConnectionInstance.registerCallbacks();
365 //You were owner of the device, but now you are not. With the current ownership
366 //grant mechanism, this scenario should not occur. Because this scenario will occur
367 //when this controller went down or switch flap the connection, but in both the case
368 //it will go through the re-registration process. We need to implement this condition
369 //when clustering service implement a ownership grant strategy which can revoke the
370 //device ownership for load balancing the devices across the instances.
371 //Once this condition occur, we should unregister the callback.
372 LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}",
373 hwvtepConnectionInstance.getNodeId().getValue());
377 private void cleanEntityOperationalData(Entity entity) {
378 //TODO: remove entity from Operational DataStore
379 LOG.error("cleanEntityOperationalData(): Code incomplete");
382 private HwvtepConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
383 return entityConnectionMap.get(entity);
386 private class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
387 private HwvtepConnectionManager hcm;
388 private EntityOwnershipListenerRegistration listenerRegistration;
390 HwvtepDeviceEntityOwnershipListener(HwvtepConnectionManager hcm, EntityOwnershipService entityOwnershipService) {
392 listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
394 public void close() {
395 listenerRegistration.close();
398 public void ownershipChanged(EntityOwnershipChange ownershipChange) {
399 hcm.handleOwnershipChanged(ownershipChange);