Merge "Fix IT tests as per as API change in SFC"
[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.TransactionInvoker;
35 import org.opendaylight.ovsdb.lib.OvsdbClient;
36 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
37 import org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService;
38 import org.opendaylight.ovsdb.lib.operations.Operation;
39 import org.opendaylight.ovsdb.lib.operations.OperationResult;
40 import org.opendaylight.ovsdb.lib.operations.Select;
41 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
42 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
43 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
44 import org.opendaylight.ovsdb.schema.hardwarevtep.Global;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalSwitchAttributes;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.PhysicalSwitchAugmentation;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ConnectionInfo;
49 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
50 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 import com.google.common.base.Optional;
56 import com.google.common.base.Preconditions;
57
58 public class HwvtepConnectionManager implements OvsdbConnectionListener, AutoCloseable{
59     private Map<ConnectionInfo, HwvtepConnectionInstance> clients = new ConcurrentHashMap<>();
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 = new ConcurrentHashMap<>();
66     private Map<Entity, HwvtepConnectionInstance> entityConnectionMap = new ConcurrentHashMap<>();
67     private EntityOwnershipService entityOwnershipService;
68     private HwvtepDeviceEntityOwnershipListener hwvtepDeviceEntityOwnershipListener;
69
70     public HwvtepConnectionManager(DataBroker db, TransactionInvoker txInvoker,
71                     EntityOwnershipService entityOwnershipService) {
72         this.db = db;
73         this.txInvoker = txInvoker;
74         this.entityOwnershipService = entityOwnershipService;
75         this.hwvtepDeviceEntityOwnershipListener = new HwvtepDeviceEntityOwnershipListener(this,entityOwnershipService);
76     }
77
78     @Override
79     public void close() throws Exception {
80         if (hwvtepDeviceEntityOwnershipListener != null) {
81             hwvtepDeviceEntityOwnershipListener.close();
82         }
83
84         for (OvsdbClient client: clients.values()) {
85             client.disconnect();
86         }
87     }
88
89     @Override
90     public void connected(@Nonnull final OvsdbClient client) {
91         HwvtepConnectionInstance hwClient = connectedButCallBacksNotRegistered(client);
92         registerEntityForOwnership(hwClient);
93         LOG.trace("connected client: {}", client);
94     }
95
96     @Override
97     public void disconnected(OvsdbClient client) {
98         LOG.info("HWVTEP Disconnected from {}:{}. Cleaning up the operational data store"
99                         ,client.getConnectionInfo().getRemoteAddress(),
100                         client.getConnectionInfo().getRemotePort());
101         ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(client);
102         HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
103         if (hwvtepConnectionInstance != null) {
104             //TODO: remove all the hwvtep nodes
105             txInvoker.invoke(new HwvtepGlobalRemoveCommand(hwvtepConnectionInstance, null, null));
106             removeConnectionInstance(key);
107
108             // Unregister Cluster Ownership for ConnectionInfo
109             unregisterEntityForOwnership(hwvtepConnectionInstance);
110         } else {
111             LOG.warn("HWVTEP disconnected event did not find connection instance for {}", key);
112         }
113         LOG.trace("disconnected client: {}", client);
114     }
115
116     public OvsdbClient connect(InstanceIdentifier<Node> iid, HwvtepGlobalAugmentation hwvtepGlobal) throws UnknownHostException {
117         InetAddress ip = HwvtepSouthboundMapper.createInetAddress(hwvtepGlobal.getConnectionInfo().getRemoteIp());
118         OvsdbClient client = OvsdbConnectionService.getService()
119                         .connect(ip, hwvtepGlobal.getConnectionInfo().getRemotePort().getValue());
120         if(client != null) {
121             putInstanceIdentifier(hwvtepGlobal.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
122             HwvtepConnectionInstance hwvtepConnectionInstance = connectedButCallBacksNotRegistered(client);
123             hwvtepConnectionInstance.setHwvtepGlobalAugmentation(hwvtepGlobal);
124             hwvtepConnectionInstance.setInstanceIdentifier(iid.firstIdentifierOf(Node.class));
125
126             // Register Cluster Ownership for ConnectionInfo
127             registerEntityForOwnership(hwvtepConnectionInstance);
128         } else {
129             LOG.warn("Failed to connect to OVSDB node: {}", hwvtepGlobal.getConnectionInfo());
130         }
131         return client;
132     }
133     public void disconnect(HwvtepGlobalAugmentation ovsdbNode) throws UnknownHostException {
134         HwvtepConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
135         if (client != null) {
136             client.disconnect();
137             // Unregister Cluster Ownership for ConnectionInfo
138             unregisterEntityForOwnership(client);
139             removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
140         }
141     }
142
143     public HwvtepConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
144         LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
145                 externalClient.getConnectionInfo().getRemotePort());
146         ConnectionInfo key = HwvtepSouthboundMapper.createConnectionInfo(externalClient);
147         HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstance(key);
148
149         // Check if existing hwvtepConnectionInstance for the OvsdbClient present.
150         // In such cases, we will see if the hwvtepConnectionInstance has same externalClient.
151         if (hwvtepConnectionInstance != null) {
152             if (hwvtepConnectionInstance.hasOvsdbClient(externalClient)) {
153                 LOG.warn("HWVTEP Connection Instance {} already exists for client {}", key, externalClient);
154                 return hwvtepConnectionInstance;
155             }
156             LOG.warn("HWVTEP Connection Instance {} being replaced with client {}", key, externalClient);
157             hwvtepConnectionInstance.disconnect();
158
159             // Unregister Cluster Ownership for ConnectionInfo
160             // Because the hwvtepConnectionInstance is about to be completely replaced!
161             unregisterEntityForOwnership(hwvtepConnectionInstance);
162
163             removeConnectionInstance(key);
164         }
165
166         hwvtepConnectionInstance = new HwvtepConnectionInstance(key, externalClient, getInstanceIdentifier(key),
167                 txInvoker);
168         hwvtepConnectionInstance.createTransactInvokers();
169         return hwvtepConnectionInstance;
170     }
171
172     private void putConnectionInstance(ConnectionInfo key,HwvtepConnectionInstance instance) {
173         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
174         clients.put(connectionInfo, instance);
175         LOG.info("Clients after put: {}", clients);
176     }
177
178     public HwvtepConnectionInstance getConnectionInstance(ConnectionInfo key) {
179         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
180         return clients.get(connectionInfo);
181     }
182
183     public HwvtepConnectionInstance getConnectionInstance(Node node) {
184         Preconditions.checkNotNull(node);
185         HwvtepGlobalAugmentation hwvtepGlobal = node.getAugmentation(HwvtepGlobalAugmentation.class);
186         PhysicalSwitchAugmentation pSwitchNode = node.getAugmentation(PhysicalSwitchAugmentation.class);
187         if (hwvtepGlobal != null) {
188             if(hwvtepGlobal.getConnectionInfo() != null) {
189                 return getConnectionInstance(hwvtepGlobal.getConnectionInfo());
190             } else {
191                 // TODO: Case of user configured connection
192                 return null; //for now
193             }
194         } //TODO: We could get it from Managers also.
195         else if(pSwitchNode != null){
196             return getConnectionInstance(pSwitchNode);
197         } else {
198             LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
199             return null;
200         }
201     }
202
203     private HwvtepConnectionInstance getConnectionInstance(HwvtepPhysicalSwitchAttributes pNode) {
204         Optional<HwvtepGlobalAugmentation> optional = HwvtepSouthboundUtil.getManagingNode(db, pNode);
205         if(optional.isPresent()) {
206             return getConnectionInstance(optional.get().getConnectionInfo());
207         } else {
208             return null;
209         }
210     }
211
212     private void removeConnectionInstance(ConnectionInfo key) {
213         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
214         clients.remove(connectionInfo);
215         LOG.info("Clients after remove: {}", clients);
216     }
217
218     private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
219         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
220         instanceIdentifiers.put(connectionInfo, iid);
221     }
222
223     public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
224         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
225         return instanceIdentifiers.get(connectionInfo);
226     }
227
228     private void removeInstanceIdentifier(ConnectionInfo key) {
229         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
230         instanceIdentifiers.remove(connectionInfo);
231     }
232
233     public OvsdbClient getClient(ConnectionInfo connectionInfo) {
234         return getConnectionInstance(connectionInfo);
235     }
236
237     private void registerEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
238
239         Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
240         entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
241         hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
242
243         try {
244             EntityOwnershipCandidateRegistration registration =
245                     entityOwnershipService.registerCandidate(candidateEntity);
246             hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
247             LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
248
249             //If entity already has owner, it won't get notification from EntityOwnershipService
250             //so cache the connection instances.
251             Optional<EntityOwnershipState> ownershipStateOpt =
252                     entityOwnershipService.getOwnershipState(candidateEntity);
253             if (ownershipStateOpt.isPresent()) {
254                 EntityOwnershipState ownershipState = ownershipStateOpt.get();
255                 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
256                     if (getConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo()) != null) {
257                         LOG.info("OVSDB entity {} is already owned by other southbound plugin "
258                                 + "instance, so *this* instance is NOT an OWNER of the device",
259                                 hwvtepConnectionInstance.getConnectionInfo());
260                         putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
261                     }
262                 }
263             }
264         } catch (CandidateAlreadyRegisteredException e) {
265             LOG.warn("OVSDB entity {} was already registered for {} ownership", candidateEntity, e);
266         }
267
268     }
269
270     private Global getHwvtepGlobalTableEntry(HwvtepConnectionInstance connectionInstance) {
271         DatabaseSchema dbSchema = null;
272         Global globalRow = null;
273
274         try {
275             dbSchema = connectionInstance.getSchema(HwvtepSchemaConstants.databaseName).get();
276         } catch (InterruptedException | ExecutionException e) {
277             LOG.warn("Not able to fetch schema for database {} from device {}",
278                     HwvtepSchemaConstants.databaseName,connectionInstance.getConnectionInfo(),e);
279         }
280
281         if (dbSchema != null) {
282             GenericTableSchema hwvtepSchema = TyperUtils.getTableSchema(dbSchema, Global.class);
283
284             List<String> hwvtepTableColumn = new ArrayList<>();
285             hwvtepTableColumn.addAll(hwvtepSchema.getColumns());
286             Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
287             selectOperation.setColumns(hwvtepTableColumn);
288
289             ArrayList<Operation> operations = new ArrayList<>();
290             operations.add(selectOperation);
291             operations.add(op.comment("Fetching hardware_vtep table rows"));
292
293             try {
294                 List<OperationResult> results = connectionInstance.transact(dbSchema, operations).get();
295                 if (results != null ) {
296                     OperationResult selectResult = results.get(0);
297                     globalRow = TyperUtils.getTypedRowWrapper(
298                             dbSchema,Global.class,selectResult.getRows().get(0));
299                 }
300             } catch (InterruptedException | ExecutionException e) {
301                 LOG.warn("Not able to fetch hardware_vtep table row from device {}",
302                         connectionInstance.getConnectionInfo(),e);
303             }
304         }
305         LOG.trace("Fetched global {} from hardware_vtep schema",globalRow);
306         return globalRow;
307     }
308
309     private Entity getEntityFromConnectionInstance(@Nonnull HwvtepConnectionInstance hwvtepConnectionInstance) {
310         InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
311         if ( iid == null ) {
312             //TODO: Is Global the right one?
313             Global hwvtepGlobalRow = getHwvtepGlobalTableEntry(hwvtepConnectionInstance);
314             iid = HwvtepSouthboundMapper.getInstanceIdentifier(hwvtepGlobalRow);
315             /* Let's set the iid now */
316             hwvtepConnectionInstance.setInstanceIdentifier(iid);
317             LOG.info("InstanceIdentifier {} generated for device "
318                     + "connection {}",iid, hwvtepConnectionInstance.getConnectionInfo());
319
320         }
321         YangInstanceIdentifier entityId =
322                 HwvtepSouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
323         Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
324         LOG.debug("Entity {} created for device connection {}",
325                 deviceEntity, hwvtepConnectionInstance.getConnectionInfo());
326         return deviceEntity;
327     }
328     private void unregisterEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
329         hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
330         entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
331     }
332
333     public void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
334         HwvtepConnectionInstance hwvtepConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
335         LOG.info("handleOwnershipChanged: {} event received for device {}",
336                 ownershipChange, hwvtepConnectionInstance != null ? hwvtepConnectionInstance.getConnectionInfo()
337                         : "THAT'S NOT REGISTERED BY THIS SOUTHBOUND PLUGIN INSTANCE");
338
339         if (hwvtepConnectionInstance == null) {
340             if (ownershipChange.isOwner()) {
341                 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
342             } else {
343                 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
344                 // that instance registered for the device ownership or not. It is to make sure that
345                 // If all the controller instance that was connected to the device are down, so the
346                 // running instance can clear up the operational data store even though it was not
347                 // connected to the device.
348                 LOG.debug("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
349             }
350
351             // If entity has no owner, clean up the operational data store (it's possible because owner controller
352             // might went down abruptly and didn't get a chance to clean up the operational data store.
353             if (!ownershipChange.hasOwner()) {
354                 LOG.debug("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
355                 // Below code might look weird but it's required. We want to give first opportunity to the
356                 // previous owner of the device to clean up the operational data store if there is no owner now.
357                 // That way we will avoid lot of nasty md-sal exceptions because of concurrent delete.
358                 if (ownershipChange.wasOwner()) {
359                     cleanEntityOperationalData(ownershipChange.getEntity());
360                 }
361                 // If first cleanEntityOperationalData() was called, this call will be no-op.
362                 cleanEntityOperationalData(ownershipChange.getEntity());
363             }
364             return;
365         }
366         //Connection detail need to be cached, irrespective of ownership result.
367         putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
368
369         if (ownershipChange.isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
370             LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
371                     hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
372             return;
373         }
374
375         hwvtepConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
376         // You were not an owner, but now you are
377         if (ownershipChange.isOwner()) {
378             LOG.info("handleOwnershipChanged: *this* southbound plugin instance is owner of device {}",
379                     hwvtepConnectionInstance.getConnectionInfo());
380
381             //*this* instance of southbound plugin is owner of the device,
382             //so register for monitor callbacks
383             hwvtepConnectionInstance.registerCallbacks();
384
385         } else {
386             //You were owner of the device, but now you are not. With the current ownership
387             //grant mechanism, this scenario should not occur. Because this scenario will occur
388             //when this controller went down or switch flap the connection, but in both the case
389             //it will go through the re-registration process. We need to implement this condition
390             //when clustering service implement a ownership grant strategy which can revoke the
391             //device ownership for load balancing the devices across the instances.
392             //Once this condition occur, we should unregister the callback.
393             LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}",
394                     hwvtepConnectionInstance.getNodeId().getValue());
395         }
396     }
397
398     private void cleanEntityOperationalData(Entity entity) {
399         InstanceIdentifier<Node> nodeIid = (InstanceIdentifier<Node>) HwvtepSouthboundUtil
400                 .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
401
402         final ReadWriteTransaction transaction = db.newReadWriteTransaction();
403         Optional<Node> node = HwvtepSouthboundUtil.readNode(transaction, nodeIid);
404         if (node.isPresent()) {
405             HwvtepSouthboundUtil.deleteNode(transaction, nodeIid);
406         }
407     }
408
409     private HwvtepConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
410         return entityConnectionMap.get(entity);
411     }
412
413     private class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
414         private HwvtepConnectionManager hcm;
415         private EntityOwnershipListenerRegistration listenerRegistration;
416
417         HwvtepDeviceEntityOwnershipListener(HwvtepConnectionManager hcm, EntityOwnershipService entityOwnershipService) {
418             this.hcm = hcm;
419             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
420         }
421         public void close() {
422             listenerRegistration.close();
423         }
424         @Override
425         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
426             hcm.handleOwnershipChanged(ownershipChange);
427         }
428     }
429 }