Merge "[Bug 5131]- Hard-coded base url in Ovsdb-ui"
[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.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;
56
57 import com.google.common.base.Optional;
58 import com.google.common.base.Preconditions;
59
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";
64
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;
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         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);
101     }
102
103     @Override
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);
117
118             // Unregister Cluster Ownership for ConnectionInfo
119             unregisterEntityForOwnership(hwvtepConnectionInstance);
120         } else {
121             LOG.warn("HWVTEP disconnected event did not find connection instance for {}", key);
122         }
123         LOG.trace("HwvtepConnectionManager exit disconnected client: {}", client);
124     }
125
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());
131         if(client != null) {
132             putInstanceIdentifier(hwvtepGlobal.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
133             HwvtepConnectionInstance hwvtepConnectionInstance = connectedButCallBacksNotRegistered(client);
134             hwvtepConnectionInstance.setHwvtepGlobalAugmentation(hwvtepGlobal);
135             hwvtepConnectionInstance.setInstanceIdentifier(iid.firstIdentifierOf(Node.class));
136
137             // Register Cluster Ownership for ConnectionInfo
138             registerEntityForOwnership(hwvtepConnectionInstance);
139         } else {
140             LOG.warn("Failed to connect to OVSDB node: {}", hwvtepGlobal.getConnectionInfo());
141         }
142         return client;
143     }
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) {
148             client.disconnect();
149             // Unregister Cluster Ownership for ConnectionInfo
150             unregisterEntityForOwnership(client);
151             removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
152         }
153     }
154
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);
160
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;
167             }
168             LOG.warn("HWVTEP Connection Instance {} being replaced with client {}", key, externalClient);
169             hwvtepConnectionInstance.disconnect();
170
171             // Unregister Cluster Ownership for ConnectionInfo
172             // Because the hwvtepConnectionInstance is about to be completely replaced!
173             unregisterEntityForOwnership(hwvtepConnectionInstance);
174
175             removeConnectionInstance(key);
176         }
177
178         hwvtepConnectionInstance = new HwvtepConnectionInstance(key, externalClient, getInstanceIdentifier(key),
179                 txInvoker);
180         hwvtepConnectionInstance.createTransactInvokers();
181         return hwvtepConnectionInstance;
182     }
183
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);
188     }
189
190     public HwvtepConnectionInstance getConnectionInstance(ConnectionInfo key) {
191         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
192         return clients.get(connectionInfo);
193     }
194
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());
202             } else {
203                 // TODO: Case of user configured connection
204                 return null; //for now
205             }
206         } //TODO: We could get it from Managers also.
207         else if(pSwitchNode != null){
208             return getConnectionInstance(pSwitchNode);
209         } else {
210             LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
211             return null;
212         }
213     }
214
215     private HwvtepConnectionInstance getConnectionInstance(HwvtepPhysicalSwitchAttributes pNode) {
216         Optional<HwvtepGlobalAugmentation> optional = HwvtepSouthboundUtil.getManagingNode(db, pNode);
217         if(optional.isPresent()) {
218             return getConnectionInstance(optional.get().getConnectionInfo());
219         } else {
220             return null;
221         }
222     }
223
224     private void removeConnectionInstance(ConnectionInfo key) {
225         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
226         clients.remove(connectionInfo);
227         LOG.info("Clients after remove: {}", clients);
228     }
229
230     private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
231         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
232         instanceIdentifiers.put(connectionInfo, iid);
233     }
234
235     public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
236         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
237         return instanceIdentifiers.get(connectionInfo);
238     }
239
240     private void removeInstanceIdentifier(ConnectionInfo key) {
241         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
242         instanceIdentifiers.remove(connectionInfo);
243     }
244
245     public OvsdbClient getClient(ConnectionInfo connectionInfo) {
246         return getConnectionInstance(connectionInfo);
247     }
248
249     private void registerEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
250
251         Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
252         entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
253         hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
254
255         try {
256             EntityOwnershipCandidateRegistration registration =
257                     entityOwnershipService.registerCandidate(candidateEntity);
258             hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
259             LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
260
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);
273                     }
274                 }
275             }
276         } catch (CandidateAlreadyRegisteredException e) {
277             LOG.warn("OVSDB entity {} was already registered for {} ownership", candidateEntity, e);
278         }
279
280     }
281
282     private Global getHwvtepGlobalTableEntry(HwvtepConnectionInstance connectionInstance) {
283         DatabaseSchema dbSchema = null;
284         Global globalRow = null;
285
286         try {
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);
291         }
292
293         if (dbSchema != null) {
294             GenericTableSchema hwvtepSchema = TyperUtils.getTableSchema(dbSchema, Global.class);
295
296             List<String> hwvtepTableColumn = new ArrayList<>();
297             hwvtepTableColumn.addAll(hwvtepSchema.getColumns());
298             Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
299             selectOperation.setColumns(hwvtepTableColumn);
300
301             ArrayList<Operation> operations = new ArrayList<>();
302             operations.add(selectOperation);
303             operations.add(op.comment("Fetching hardware_vtep table rows"));
304
305             try {
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));
311                 }
312             } catch (InterruptedException | ExecutionException e) {
313                 LOG.warn("Not able to fetch hardware_vtep table row from device {}",
314                         connectionInstance.getConnectionInfo(),e);
315             }
316         }
317         LOG.trace("Fetched global {} from hardware_vtep schema",globalRow);
318         return globalRow;
319     }
320
321     private Entity getEntityFromConnectionInstance(@Nonnull HwvtepConnectionInstance hwvtepConnectionInstance) {
322         InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
323         if ( iid == null ) {
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());
331
332         }
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());
338         return deviceEntity;
339     }
340     private void unregisterEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
341         hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
342         entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
343     }
344
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");
350
351         if (hwvtepConnectionInstance == null) {
352             if (ownershipChange.isOwner()) {
353                 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
354             } else {
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());
361             }
362
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());
372                 }
373                 // If first cleanEntityOperationalData() was called, this call will be no-op.
374                 cleanEntityOperationalData(ownershipChange.getEntity());
375             }
376             return;
377         }
378         //Connection detail need to be cached, irrespective of ownership result.
379         putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
380
381         if (ownershipChange.isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
382             LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
383                     hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
384             return;
385         }
386
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());
392
393             //*this* instance of southbound plugin is owner of the device,
394             //so register for monitor callbacks
395             hwvtepConnectionInstance.registerCallbacks();
396
397         } else {
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());
407         }
408     }
409
410     private void cleanEntityOperationalData(Entity entity) {
411         @SuppressWarnings("unchecked") final InstanceIdentifier<Node> nodeIid =
412                 (InstanceIdentifier<Node>) HwvtepSouthboundUtil
413                         .getInstanceIdentifierCodec().bindingDeserializer(entity.getId());
414
415         txInvoker.invoke(new TransactionCommand() {
416             @Override
417             public void execute(ReadWriteTransaction transaction) {
418                 transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
419             }
420         });
421     }
422
423     private HwvtepConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
424         return entityConnectionMap.get(entity);
425     }
426
427     private class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
428         private HwvtepConnectionManager hcm;
429         private EntityOwnershipListenerRegistration listenerRegistration;
430
431         HwvtepDeviceEntityOwnershipListener(HwvtepConnectionManager hcm, EntityOwnershipService entityOwnershipService) {
432             this.hcm = hcm;
433             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
434         }
435         public void close() {
436             listenerRegistration.close();
437         }
438         @Override
439         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
440             hcm.handleOwnershipChanged(ownershipChange);
441         }
442     }
443 }