bac5a71b763b33f4f6fc890bd08aac89dd146c4c
[ovsdb.git] / hwvtepsouthbound / hwvtepsouthbound-impl / src / main / java / org / opendaylight / ovsdb / hwvtepsouthbound / HwvtepConnectionManager.java
1 /*
2  * Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.ovsdb.hwvtepsouthbound;
10
11 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
12
13 import java.net.InetAddress;
14 import java.net.UnknownHostException;
15 import java.util.ArrayList;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ExecutionException;
20
21 import javax.annotation.Nonnull;
22
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;
53
54 import com.google.common.base.Optional;
55 import com.google.common.base.Preconditions;
56
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";
62
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;
71
72     public HwvtepConnectionManager(DataBroker db, TransactionInvoker txInvoker,
73                     EntityOwnershipService entityOwnershipService) {
74         this.db = db;
75         this.txInvoker = txInvoker;
76         this.entityOwnershipService = entityOwnershipService;
77         this.hwvtepDeviceEntityOwnershipListener = new HwvtepDeviceEntityOwnershipListener(this,entityOwnershipService);
78     }
79
80     @Override
81     public void close() throws Exception {
82         if (hwvtepDeviceEntityOwnershipListener != null) {
83             hwvtepDeviceEntityOwnershipListener.close();
84         }
85
86         for (OvsdbClient client: clients.values()) {
87             client.disconnect();
88         }
89     }
90
91     @Override
92     public void connected(@Nonnull final OvsdbClient client) {
93         HwvtepConnectionInstance hwClient = connectedButCallBacksNotRegistered(client);
94         registerEntityForOwnership(hwClient);
95         LOG.trace("connected client: {}", client);
96     }
97
98     @Override
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);
109
110             // Unregister Cluster Ownership for ConnectionInfo
111             unregisterEntityForOwnership(hwvtepConnectionInstance);
112         } else {
113             LOG.warn("HWVTEP disconnected event did not find connection instance for {}", key);
114         }
115         LOG.trace("disconnected client: {}", client);
116     }
117
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());
122         if(client != null) {
123             putInstanceIdentifier(hwvtepGlobal.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
124             HwvtepConnectionInstance hwvtepConnectionInstance = connectedButCallBacksNotRegistered(client);
125             hwvtepConnectionInstance.setHwvtepGlobalAugmentation(hwvtepGlobal);
126             hwvtepConnectionInstance.setInstanceIdentifier(iid.firstIdentifierOf(Node.class));
127
128             // Register Cluster Ownership for ConnectionInfo
129             registerEntityForOwnership(hwvtepConnectionInstance);
130         } else {
131             LOG.warn("Failed to connect to OVSDB node: {}", hwvtepGlobal.getConnectionInfo());
132         }
133         return client;
134     }
135     public void disconnect(HwvtepGlobalAugmentation ovsdbNode) throws UnknownHostException {
136         HwvtepConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
137         if (client != null) {
138             client.disconnect();
139             // Unregister Cluster Ownership for ConnectionInfo
140             unregisterEntityForOwnership(client);
141             removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
142         }
143     }
144
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);
150
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;
157             }
158             LOG.warn("HWVTEP Connection Instance {} being replaced with client {}", key, externalClient);
159             hwvtepConnectionInstance.disconnect();
160
161             // Unregister Cluster Ownership for ConnectionInfo
162             // Because the hwvtepConnectionInstance is about to be completely replaced!
163             unregisterEntityForOwnership(hwvtepConnectionInstance);
164
165             removeConnectionInstance(key);
166         }
167
168         hwvtepConnectionInstance = new HwvtepConnectionInstance(key, externalClient, getInstanceIdentifier(key),
169                 txInvoker);
170         hwvtepConnectionInstance.createTransactInvokers();
171         return hwvtepConnectionInstance;
172     }
173
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);
178     }
179
180     public HwvtepConnectionInstance getConnectionInstance(ConnectionInfo key) {
181         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
182         return clients.get(connectionInfo);
183     }
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.
190         else {
191             LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
192             return null;
193         }
194     }
195
196     private void removeConnectionInstance(ConnectionInfo key) {
197         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
198         clients.remove(connectionInfo);
199         LOG.info("Clients after remove: {}", clients);
200     }
201
202     private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
203         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
204         instanceIdentifiers.put(connectionInfo, iid);
205     }
206
207     public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
208         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
209         InstanceIdentifier<Node> iid = instanceIdentifiers.get(connectionInfo);
210         return iid;
211     }
212
213     private void removeInstanceIdentifier(ConnectionInfo key) {
214         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
215         instanceIdentifiers.remove(connectionInfo);
216     }
217
218     public OvsdbClient getClient(ConnectionInfo connectionInfo) {
219         return getConnectionInstance(connectionInfo);
220     }
221
222     private void registerEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
223
224         Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
225         entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
226         hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
227
228         try {
229             EntityOwnershipCandidateRegistration registration =
230                     entityOwnershipService.registerCandidate(candidateEntity);
231             hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
232             LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
233
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);
246                     }
247                 }
248             }
249         } catch (CandidateAlreadyRegisteredException e) {
250             LOG.warn("OVSDB entity {} was already registered for {} ownership", candidateEntity, e);
251         }
252
253     }
254
255     private Global getHwvtepGlobalTableEntry(HwvtepConnectionInstance connectionInstance) {
256         DatabaseSchema dbSchema = null;
257         Global globalRow = null;
258
259         try {
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);
264         }
265
266         if (dbSchema != null) {
267             GenericTableSchema hwvtepSchema = TyperUtils.getTableSchema(dbSchema, Global.class);
268
269             List<String> hwvtepTableColumn = new ArrayList<String>();
270             hwvtepTableColumn.addAll(hwvtepSchema.getColumns());
271             Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
272             selectOperation.setColumns(hwvtepTableColumn);;
273
274             ArrayList<Operation> operations = new ArrayList<Operation>();
275             operations.add(selectOperation);
276             operations.add(op.comment("Fetching hardware_vtep table rows"));
277
278             List<OperationResult> results = null;
279             try {
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));
285                 }
286             } catch (InterruptedException | ExecutionException e) {
287                 LOG.warn("Not able to fetch hardware_vtep table row from device {}",
288                         connectionInstance.getConnectionInfo(),e);
289             }
290         }
291         LOG.trace("Fetched global {} from hardware_vtep schema",globalRow);
292         return globalRow;
293     }
294
295     private Entity getEntityFromConnectionInstance(@Nonnull HwvtepConnectionInstance hwvtepConnectionInstance) {
296         YangInstanceIdentifier entityId = null;
297         InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
298         if ( iid == null ) {
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());
306
307         }
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());
312         return deviceEntity;
313     }
314     private void unregisterEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
315         hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
316         entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
317     }
318
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");
324
325         if (hwvtepConnectionInstance == null) {
326             if (ownershipChange.isOwner()) {
327                 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
328             } else {
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());
335             }
336
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());
346                 }
347                 // If first cleanEntityOperationalData() was called, this call will be no-op.
348                 cleanEntityOperationalData(ownershipChange.getEntity());
349             }
350             return;
351         }
352         //Connection detail need to be cached, irrespective of ownership result.
353         putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
354
355         if (ownershipChange.isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
356             LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
357                     hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
358             return;
359         }
360
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());
366
367             //*this* instance of southbound plugin is owner of the device,
368             //so register for monitor callbacks
369             hwvtepConnectionInstance.registerCallbacks();
370
371         } else {
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());
381         }
382     }
383
384     private void cleanEntityOperationalData(Entity entity) {
385         InstanceIdentifier<Node> nodeIid = (InstanceIdentifier<Node>) HwvtepSouthboundUtil
386                 .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
387
388         final ReadWriteTransaction transaction = db.newReadWriteTransaction();
389         Optional<Node> node = HwvtepSouthboundUtil.readNode(transaction, nodeIid);
390         if (node.isPresent()) {
391             HwvtepSouthboundUtil.deleteNode(transaction, nodeIid);
392         }
393     }
394
395     private HwvtepConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
396         return entityConnectionMap.get(entity);
397     }
398
399     private class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
400         private HwvtepConnectionManager hcm;
401         private EntityOwnershipListenerRegistration listenerRegistration;
402
403         HwvtepDeviceEntityOwnershipListener(HwvtepConnectionManager hcm, EntityOwnershipService entityOwnershipService) {
404             this.hcm = hcm;
405             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
406         }
407         public void close() {
408             listenerRegistration.close();
409         }
410         @Override
411         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
412             hcm.handleOwnershipChanged(ownershipChange);
413         }
414     }
415
416 }