Add DataTreeChangeListener, user connections
[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.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;
50
51 import com.google.common.base.Optional;
52
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";
58
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;
67
68     public HwvtepConnectionManager(DataBroker db, TransactionInvoker txInvoker,
69                     EntityOwnershipService entityOwnershipService) {
70         this.db = db;
71         this.txInvoker = txInvoker;
72         this.entityOwnershipService = entityOwnershipService;
73         this.hwvtepDeviceEntityOwnershipListener = new HwvtepDeviceEntityOwnershipListener(this,entityOwnershipService);
74     }
75
76     @Override
77     public void close() throws Exception {
78         if (hwvtepDeviceEntityOwnershipListener != null) {
79             hwvtepDeviceEntityOwnershipListener.close();
80         }
81
82         for (OvsdbClient client: clients.values()) {
83             client.disconnect();
84         }
85     }
86
87     @Override
88     public void connected(@Nonnull final OvsdbClient client) {
89         HwvtepConnectionInstance hwClient = connectedButCallBacksNotRegistered(client);
90         registerEntityForOwnership(hwClient);
91         LOG.trace("connected client: {}", client);
92     }
93
94     @Override
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);
104
105             // Unregister Cluster Ownership for ConnectionInfo
106             unregisterEntityForOwnership(hwvtepConnectionInstance);
107         } else {
108             LOG.warn("HWVTEP disconnected event did not find connection instance for {}", key);
109         }
110         LOG.trace("disconnected client: {}", client);
111     }
112
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());
117         if(client != null) {
118             putInstanceIdentifier(hwvtepGlobal.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
119             HwvtepConnectionInstance hwvtepConnectionInstance = connectedButCallBacksNotRegistered(client);
120             hwvtepConnectionInstance.setHwvtepGlobalAugmentation(hwvtepGlobal);
121
122             // Register Cluster Ownership for ConnectionInfo
123             registerEntityForOwnership(hwvtepConnectionInstance);
124         } else {
125             LOG.warn("Failed to connect to OVSDB node: {}", hwvtepGlobal.getConnectionInfo());
126         }
127         return client;
128     }
129     public void disconnect(HwvtepGlobalAugmentation ovsdbNode) throws UnknownHostException {
130         HwvtepConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
131         if (client != null) {
132             client.disconnect();
133             // Unregister Cluster Ownership for ConnectionInfo
134             unregisterEntityForOwnership(client);
135             removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
136         }
137     }
138
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);
144
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;
151             }
152             LOG.warn("HWVTEP Connection Instance {} being replaced with client {}", key, externalClient);
153             hwvtepConnectionInstance.disconnect();
154
155             // Unregister Cluster Ownership for ConnectionInfo
156             // Because the hwvtepConnectionInstance is about to be completely replaced!
157             unregisterEntityForOwnership(hwvtepConnectionInstance);
158
159             removeConnectionInstance(key);
160         }
161
162         hwvtepConnectionInstance = new HwvtepConnectionInstance(key, externalClient, getInstanceIdentifier(key),
163                 txInvoker);
164         hwvtepConnectionInstance.createTransactInvokers();
165         return hwvtepConnectionInstance;
166     }
167
168     /* TODO:
169     public OvsdbClient connect(InstanceIdentifier<Node> iid, OvsdbNodeAugmentation ovsdbNode)
170                     throws UnknownHostException {
171     }
172
173     public void disconnect(OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
174         OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
175
176     }
177
178     */
179
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);
184     }
185
186     public HwvtepConnectionInstance getConnectionInstance(ConnectionInfo key) {
187         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
188         return clients.get(connectionInfo);
189     }
190
191     private void removeConnectionInstance(ConnectionInfo key) {
192         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
193         clients.remove(connectionInfo);
194         LOG.info("Clients after remove: {}", clients);
195     }
196
197     private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
198         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
199         instanceIdentifiers.put(connectionInfo, iid);
200     }
201
202     public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
203         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
204         InstanceIdentifier<Node> iid = instanceIdentifiers.get(connectionInfo);
205         return iid;
206     }
207
208     private void removeInstanceIdentifier(ConnectionInfo key) {
209         ConnectionInfo connectionInfo = HwvtepSouthboundMapper.suppressLocalIpPort(key);
210         instanceIdentifiers.remove(connectionInfo);
211     }
212
213     public OvsdbClient getClient(ConnectionInfo connectionInfo) {
214         return getConnectionInstance(connectionInfo);
215     }
216
217     private void registerEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
218
219         Entity candidateEntity = getEntityFromConnectionInstance(hwvtepConnectionInstance);
220         entityConnectionMap.put(candidateEntity, hwvtepConnectionInstance);
221         hwvtepConnectionInstance.setConnectedEntity(candidateEntity);
222
223         try {
224             EntityOwnershipCandidateRegistration registration =
225                     entityOwnershipService.registerCandidate(candidateEntity);
226             hwvtepConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
227             LOG.info("HWVTEP entity {} is registered for ownership.", candidateEntity);
228
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);
241                     }
242                 }
243             }
244         } catch (CandidateAlreadyRegisteredException e) {
245             LOG.warn("OVSDB entity {} was already registered for {} ownership", candidateEntity, e);
246         }
247
248     }
249
250     private Global getHwvtepGlobalTableEntry(HwvtepConnectionInstance connectionInstance) {
251         DatabaseSchema dbSchema = null;
252         Global globalRow = null;
253
254         try {
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);
259         }
260
261         if (dbSchema != null) {
262             GenericTableSchema hwvtepSchema = TyperUtils.getTableSchema(dbSchema, Global.class);
263
264             List<String> hwvtepTableColumn = new ArrayList<String>();
265             hwvtepTableColumn.addAll(hwvtepSchema.getColumns());
266             Select<GenericTableSchema> selectOperation = op.select(hwvtepSchema);
267             selectOperation.setColumns(hwvtepTableColumn);;
268
269             ArrayList<Operation> operations = new ArrayList<Operation>();
270             operations.add(selectOperation);
271             operations.add(op.comment("Fetching hardware_vtep table rows"));
272
273             List<OperationResult> results = null;
274             try {
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));
280                 }
281             } catch (InterruptedException | ExecutionException e) {
282                 LOG.warn("Not able to fetch hardware_vtep table row from device {}",
283                         connectionInstance.getConnectionInfo(),e);
284             }
285         }
286         LOG.trace("Fetched global {} from hardware_vtep schema",globalRow);
287         return globalRow;
288     }
289
290     private Entity getEntityFromConnectionInstance(@Nonnull HwvtepConnectionInstance hwvtepConnectionInstance) {
291         YangInstanceIdentifier entityId = null;
292         InstanceIdentifier<Node> iid = hwvtepConnectionInstance.getInstanceIdentifier();
293         if ( iid == null ) {
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());
299
300         }
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());
305         return deviceEntity;
306     }
307     private void unregisterEntityForOwnership(HwvtepConnectionInstance hwvtepConnectionInstance) {
308         hwvtepConnectionInstance.closeDeviceOwnershipCandidateRegistration();
309         entityConnectionMap.remove(hwvtepConnectionInstance.getConnectedEntity());
310     }
311
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");
317
318         if (hwvtepConnectionInstance == null) {
319             if (ownershipChange.isOwner()) {
320                 LOG.warn("handleOwnershipChanged: found no connection instance for {}", ownershipChange.getEntity());
321             } else {
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());
328             }
329
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());
339                 }
340                 // If first cleanEntityOperationalData() was called, this call will be no-op.
341                 cleanEntityOperationalData(ownershipChange.getEntity());
342             }
343             return;
344         }
345         //Connection detail need to be cached, irrespective of ownership result.
346         putConnectionInstance(hwvtepConnectionInstance.getMDConnectionInfo(),hwvtepConnectionInstance);
347
348         if (ownershipChange.isOwner() == hwvtepConnectionInstance.getHasDeviceOwnership()) {
349             LOG.debug("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
350                     hwvtepConnectionInstance.getConnectionInfo(), hwvtepConnectionInstance.getHasDeviceOwnership());
351             return;
352         }
353
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());
359
360             //*this* instance of southbound plugin is owner of the device,
361             //so register for monitor callbacks
362             hwvtepConnectionInstance.registerCallbacks();
363
364         } else {
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());
374         }
375     }
376
377     private void cleanEntityOperationalData(Entity entity) {
378         //TODO: remove entity from Operational DataStore
379         LOG.error("cleanEntityOperationalData(): Code incomplete");
380     }
381
382     private HwvtepConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
383         return entityConnectionMap.get(entity);
384     }
385
386     private class HwvtepDeviceEntityOwnershipListener implements EntityOwnershipListener {
387         private HwvtepConnectionManager hcm;
388         private EntityOwnershipListenerRegistration listenerRegistration;
389
390         HwvtepDeviceEntityOwnershipListener(HwvtepConnectionManager hcm, EntityOwnershipService entityOwnershipService) {
391             this.hcm = hcm;
392             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
393         }
394         public void close() {
395             listenerRegistration.close();
396         }
397         @Override
398         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
399             hcm.handleOwnershipChanged(ownershipChange);
400         }
401     }
402
403 }