Make TransactionBuilder type-aware
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / OvsdbConnectionManager.java
1 /*
2  * Copyright © 2014, 2017 Cisco Systems, Inc. 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 package org.opendaylight.ovsdb.southbound;
9
10 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
20 import java.net.ConnectException;
21 import java.net.InetAddress;
22 import java.net.UnknownHostException;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
32 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
33 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
34 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
35 import org.opendaylight.mdsal.eos.binding.api.Entity;
36 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
37 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
38 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
39 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
40 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
41 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
42 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
43 import org.opendaylight.ovsdb.lib.OvsdbClient;
44 import org.opendaylight.ovsdb.lib.OvsdbConnection;
45 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
46 import org.opendaylight.ovsdb.lib.operations.Operation;
47 import org.opendaylight.ovsdb.lib.operations.OperationResult;
48 import org.opendaylight.ovsdb.lib.operations.Select;
49 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
50 import org.opendaylight.ovsdb.lib.schema.typed.TypedDatabaseSchema;
51 import org.opendaylight.ovsdb.schema.openvswitch.OpenVSwitch;
52 import org.opendaylight.ovsdb.southbound.reconciliation.ReconciliationManager;
53 import org.opendaylight.ovsdb.southbound.reconciliation.ReconciliationTask;
54 import org.opendaylight.ovsdb.southbound.reconciliation.configuration.BridgeConfigReconciliationTask;
55 import org.opendaylight.ovsdb.southbound.reconciliation.connection.ConnectionReconciliationTask;
56 import org.opendaylight.ovsdb.southbound.transactions.md.OvsdbNodeRemoveCommand;
57 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
64 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoCloseable {
69     private final Map<ConnectionInfo, OvsdbConnectionInstance> clients =
70             new ConcurrentHashMap<>();
71     private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionManager.class);
72     private static final String ENTITY_TYPE = "ovsdb";
73     private static final int DB_FETCH_TIMEOUT = 1000;
74
75     private final DataBroker db;
76     private final TransactionInvoker txInvoker;
77     private final Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
78             new ConcurrentHashMap<>();
79     private final Map<InstanceIdentifier<Node>, OvsdbConnectionInstance> nodeIdVsConnectionInstance =
80             new ConcurrentHashMap<>();
81     private final Map<Entity, OvsdbConnectionInstance> entityConnectionMap =
82             new ConcurrentHashMap<>();
83     private final EntityOwnershipService entityOwnershipService;
84     private final OvsdbDeviceEntityOwnershipListener ovsdbDeviceEntityOwnershipListener;
85     private final OvsdbConnection ovsdbConnection;
86     private final ReconciliationManager reconciliationManager;
87     private final InstanceIdentifierCodec instanceIdentifierCodec;
88
89     public OvsdbConnectionManager(final DataBroker db,final TransactionInvoker txInvoker,
90                                   final EntityOwnershipService entityOwnershipService,
91                                   final OvsdbConnection ovsdbConnection,
92                                   final InstanceIdentifierCodec instanceIdentifierCodec) {
93         this.db = db;
94         this.txInvoker = txInvoker;
95         this.entityOwnershipService = entityOwnershipService;
96         this.ovsdbDeviceEntityOwnershipListener = new OvsdbDeviceEntityOwnershipListener(this, entityOwnershipService);
97         this.ovsdbConnection = ovsdbConnection;
98         this.reconciliationManager = new ReconciliationManager(db, instanceIdentifierCodec);
99         this.instanceIdentifierCodec = instanceIdentifierCodec;
100     }
101
102     @Override
103     public void connected(final OvsdbClient externalClient) {
104         LOG.info("Library connected {} from {}:{} to {}:{}",
105                 externalClient.getConnectionInfo().getType(),
106                 externalClient.getConnectionInfo().getRemoteAddress(),
107                 externalClient.getConnectionInfo().getRemotePort(),
108                 externalClient.getConnectionInfo().getLocalAddress(),
109                 externalClient.getConnectionInfo().getLocalPort());
110         try {
111             List<String> databases = externalClient.getDatabases().get(DB_FETCH_TIMEOUT, TimeUnit.MILLISECONDS);
112             if (databases.contains(SouthboundConstants.OPEN_V_SWITCH)) {
113                 OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
114                 // Register Cluster Ownership for ConnectionInfo
115                 registerEntityForOwnership(client);
116             }
117         } catch (InterruptedException | ExecutionException | TimeoutException e) {
118             LOG.warn("Unable to fetch Database list from device {}. Disconnecting from the device.",
119                     externalClient.getConnectionInfo().getRemoteAddress(), e);
120             externalClient.disconnect();
121         }
122
123     }
124
125     public OvsdbConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
126         LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
127                 externalClient.getConnectionInfo().getRemotePort());
128         ConnectionInfo key = SouthboundMapper.createConnectionInfo(externalClient);
129         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
130
131         // Check if existing ovsdbConnectionInstance for the OvsdbClient present.
132         // In such cases, we will see if the ovsdbConnectionInstance has same externalClient.
133         if (ovsdbConnectionInstance != null) {
134             if (ovsdbConnectionInstance.hasOvsdbClient(externalClient)) {
135                 LOG.warn("OVSDB Connection Instance {} already exists for client {}", key, externalClient);
136                 return ovsdbConnectionInstance;
137             }
138             LOG.warn("OVSDB Connection Instance {} being replaced with client {}", key, externalClient);
139
140             // Unregister Cluster Ownership for ConnectionInfo
141             // Because the ovsdbConnectionInstance is about to be completely replaced!
142             unregisterEntityForOwnership(ovsdbConnectionInstance);
143
144             ovsdbConnectionInstance.disconnect();
145
146             removeConnectionInstance(key);
147
148             stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
149         }
150
151         ovsdbConnectionInstance = new OvsdbConnectionInstance(key, externalClient, txInvoker,
152                 getInstanceIdentifier(key));
153         ovsdbConnectionInstance.createTransactInvokers();
154         return ovsdbConnectionInstance;
155     }
156
157     @Override
158     public void disconnected(final OvsdbClient client) {
159         LOG.info("Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
160                 client.getConnectionInfo().getType(),
161                 client.getConnectionInfo().getRemoteAddress(),
162                 client.getConnectionInfo().getRemotePort(),
163                 client.getConnectionInfo().getLocalAddress(),
164                 client.getConnectionInfo().getLocalPort());
165         ConnectionInfo key = SouthboundMapper.createConnectionInfo(client);
166         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
167         if (ovsdbConnectionInstance != null) {
168             // Unregister Entity ownership as soon as possible ,so this instance should
169             // not be used as a candidate in Entity election (given that this instance is
170             // about to disconnect as well), if current owner get disconnected from
171             // OVSDB device.
172             if (ovsdbConnectionInstance.getHasDeviceOwnership()) {
173                 LOG.info("Library disconnected {} this controller instance has ownership", key);
174                 deleteOperNodeAndReleaseOwnership(ovsdbConnectionInstance);
175             } else {
176                 LOG.info("Library disconnected {} this controller does not have ownership", key);
177                 unregisterEntityForOwnership(ovsdbConnectionInstance);
178             }
179             removeConnectionInstance(key);
180
181             //Controller initiated connection can be terminated from switch side.
182             //So cleanup the instance identifier cache.
183             removeInstanceIdentifier(key);
184             nodeIdVsConnectionInstance.remove(ovsdbConnectionInstance.getInstanceIdentifier(),
185                     ovsdbConnectionInstance);
186             stopBridgeConfigReconciliationIfActive(ovsdbConnectionInstance.getInstanceIdentifier());
187             retryConnection(ovsdbConnectionInstance.getInstanceIdentifier(),
188                     ovsdbConnectionInstance.getOvsdbNodeAugmentation(),
189                     ConnectionReconciliationTriggers.ON_DISCONNECT);
190         } else {
191             LOG.warn("disconnected : Connection instance not found for OVSDB Node {} ", key);
192         }
193         LOG.trace("OvsdbConnectionManager: exit disconnected client: {}", client);
194     }
195
196     private void deleteOperNodeAndReleaseOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
197         ovsdbConnectionInstance.setHasDeviceOwnership(false);
198         final InstanceIdentifier nodeIid = ovsdbConnectionInstance.getInstanceIdentifier();
199         //remove the node from oper only if it has ownership
200         txInvoker.invoke(new OvsdbNodeRemoveCommand(ovsdbConnectionInstance, null, null) {
201
202             @Override
203             public void onSuccess() {
204                 super.onSuccess();
205                 LOG.debug("Successfully removed node {} from oper", nodeIid);
206                 //Giveup the ownership only after cleanup is done
207                 unregisterEntityForOwnership(ovsdbConnectionInstance);
208             }
209
210             @Override
211             public void onFailure(final Throwable throwable) {
212                 LOG.debug("Failed to remove node {} from oper", nodeIid);
213                 super.onFailure(throwable);
214                 unregisterEntityForOwnership(ovsdbConnectionInstance);
215             }
216         });
217     }
218
219     public OvsdbClient connect(final InstanceIdentifier<Node> iid,
220             final OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException, ConnectException {
221         LOG.info("Connecting to {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
222
223         // TODO handle case where we already have a connection
224         // TODO use transaction chains to handle ordering issues between disconnected
225         // TODO and connected when writing to the operational store
226         InetAddress ip = SouthboundMapper.createInetAddress(ovsdbNode.getConnectionInfo().getRemoteIp());
227         OvsdbClient client = ovsdbConnection.connect(ip,
228                 ovsdbNode.getConnectionInfo().getRemotePort().getValue().toJava());
229         // For connections from the controller to the ovs instance, the library doesn't call
230         // this method for us
231         if (client != null) {
232             putInstanceIdentifier(ovsdbNode.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
233             OvsdbConnectionInstance ovsdbConnectionInstance = connectedButCallBacksNotRegistered(client);
234             ovsdbConnectionInstance.setOvsdbNodeAugmentation(ovsdbNode);
235
236             // Register Cluster Ownership for ConnectionInfo
237             registerEntityForOwnership(ovsdbConnectionInstance);
238         } else {
239             LOG.warn("Failed to connect to OVSDB Node {}", ovsdbNode.getConnectionInfo());
240         }
241         return client;
242     }
243
244     public void disconnect(final OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
245         LOG.info("Disconnecting from {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
246         OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
247         if (client != null) {
248             // Unregister Cluster Onwership for ConnectionInfo
249             deleteOperNodeAndReleaseOwnership(client);
250
251             client.disconnect();
252
253             removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
254
255             stopBridgeConfigReconciliationIfActive(client.getInstanceIdentifier());
256         } else {
257             LOG.debug("disconnect : connection instance not found for {}",ovsdbNode.getConnectionInfo());
258         }
259     }
260
261 /*    public void init(ConnectionInfo key) {
262         OvsdbConnectionInstance client = getConnectionInstance(key);
263
264         // TODO (FF): make sure that this cluster instance is the 'entity owner' fo the given OvsdbConnectionInstance ?
265
266         if (client != null) {
267
268              *  Note: registerCallbacks() is idemPotent... so if you call it repeatedly all is safe,
269              *  it only registersCallbacks on the *first* call.
270
271             client.registerCallbacks();
272         }
273     }
274 */
275     @Override
276     public void close() {
277         if (ovsdbDeviceEntityOwnershipListener != null) {
278             ovsdbDeviceEntityOwnershipListener.close();
279         }
280
281         for (OvsdbConnectionInstance client: clients.values()) {
282             client.disconnect();
283         }
284     }
285
286     @VisibleForTesting
287     void putConnectionInstance(final ConnectionInfo key,final OvsdbConnectionInstance instance) {
288         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
289         clients.put(connectionInfo, instance);
290     }
291
292     private void removeConnectionInstance(final ConnectionInfo key) {
293         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
294         clients.remove(connectionInfo);
295     }
296
297     @VisibleForTesting
298     void putInstanceIdentifier(final ConnectionInfo key, final InstanceIdentifier<Node> iid) {
299         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
300         instanceIdentifiers.put(connectionInfo, iid);
301     }
302
303     private void removeInstanceIdentifier(final ConnectionInfo key) {
304         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
305         instanceIdentifiers.remove(connectionInfo);
306     }
307
308     public InstanceIdentifier<Node> getInstanceIdentifier(final ConnectionInfo key) {
309         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
310         return instanceIdentifiers.get(connectionInfo);
311     }
312
313     public OvsdbConnectionInstance getConnectionInstance(final ConnectionInfo key) {
314         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
315         return clients.get(connectionInfo);
316     }
317
318     public OvsdbConnectionInstance getConnectionInstance(final OvsdbBridgeAttributes mn) {
319         Optional<OvsdbNodeAugmentation> optional = SouthboundUtil.getManagingNode(db, mn);
320         if (optional.isPresent()) {
321             return getConnectionInstance(optional.get().getConnectionInfo());
322         } else {
323             return null;
324         }
325     }
326
327     public OvsdbConnectionInstance getConnectionInstance(final Node node) {
328         Preconditions.checkNotNull(node);
329         OvsdbNodeAugmentation ovsdbNode = node.augmentation(OvsdbNodeAugmentation.class);
330         OvsdbBridgeAugmentation ovsdbManagedNode = node.augmentation(OvsdbBridgeAugmentation.class);
331         if (ovsdbNode != null) {
332             return getConnectionInstance(ovsdbNode.getConnectionInfo());
333         } else if (ovsdbManagedNode != null) {
334             return getConnectionInstance(ovsdbManagedNode);
335         } else {
336             LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
337             return null;
338         }
339     }
340
341     public OvsdbConnectionInstance getConnectionInstance(final InstanceIdentifier<Node> nodePath) {
342         if (nodeIdVsConnectionInstance.get(nodePath) != null) {
343             return nodeIdVsConnectionInstance.get(nodePath);
344         }
345         try {
346             ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
347             CheckedFuture<Optional<Node>, ReadFailedException> nodeFuture = transaction.read(
348                     LogicalDatastoreType.OPERATIONAL, nodePath);
349             transaction.close();
350             Optional<Node> optional = nodeFuture.get();
351             if (optional.isPresent()) {
352                 return this.getConnectionInstance(optional.get());
353             } else {
354                 LOG.debug("Node was not found on the path in the operational DS: {}", nodePath);
355                 return null;
356             }
357         } catch (InterruptedException | ExecutionException e) {
358             LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
359             return null;
360         }
361     }
362
363     public OvsdbClient getClient(final ConnectionInfo connectionInfo) {
364         OvsdbConnectionInstance connectionInstance = getConnectionInstance(connectionInfo);
365         if (connectionInstance != null) {
366             return connectionInstance.getOvsdbClient();
367         }
368         return null;
369     }
370
371     public OvsdbClient getClient(final OvsdbBridgeAttributes mn) {
372         return getConnectionInstance(mn).getOvsdbClient();
373     }
374
375     public OvsdbClient getClient(final Node node) {
376         return getConnectionInstance(node).getOvsdbClient();
377     }
378
379     public Boolean getHasDeviceOwnership(final ConnectionInfo connectionInfo) {
380         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(connectionInfo);
381         if (ovsdbConnectionInstance == null) {
382             return Boolean.FALSE;
383         }
384         return ovsdbConnectionInstance.getHasDeviceOwnership();
385     }
386
387     public void reconcileConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode) {
388         this.retryConnection(iid, ovsdbNode,
389                 ConnectionReconciliationTriggers.ON_CONTROLLER_INITIATED_CONNECTION_FAILURE);
390
391     }
392
393     public void stopConnectionReconciliationIfActive(final InstanceIdentifier<?> iid,
394             final OvsdbNodeAugmentation ovsdbNode) {
395         final ReconciliationTask task = new ConnectionReconciliationTask(
396                 reconciliationManager,
397                 this,
398                 iid,
399                 ovsdbNode);
400         reconciliationManager.dequeue(task);
401     }
402
403     public void stopBridgeConfigReconciliationIfActive(final InstanceIdentifier<?> iid) {
404         final ReconciliationTask task =
405                 new BridgeConfigReconciliationTask(reconciliationManager, this, iid, null, instanceIdentifierCodec);
406         reconciliationManager.dequeue(task);
407         reconciliationManager.cancelTerminationPointReconciliation();
408     }
409
410     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
411             justification = "https://github.com/spotbugs/spotbugs/issues/811")
412     private void handleOwnershipChanged(final EntityOwnershipChange ownershipChange) {
413         OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
414         LOG.debug("handleOwnershipChanged: {} event received for device {}",
415                 ownershipChange, ovsdbConnectionInstance != null ? ovsdbConnectionInstance.getConnectionInfo()
416                         : "that's currently NOT registered by *this* southbound plugin instance");
417
418         if (ovsdbConnectionInstance == null) {
419             if (ownershipChange.getState().isOwner()) {
420                 LOG.warn("handleOwnershipChanged: *this* instance is elected as an owner of the device {} but it "
421                         + "is NOT registered for ownership", ownershipChange.getEntity());
422             } else {
423                 // EntityOwnershipService sends notification to all the nodes, irrespective of whether
424                 // that instance registered for the device ownership or not. It is to make sure that
425                 // If all the controller instance that was connected to the device are down, so the
426                 // running instance can clear up the operational data store even though it was not
427                 // connected to the device.
428                 LOG.debug("handleOwnershipChanged: No connection instance found for {}", ownershipChange.getEntity());
429             }
430
431             // If entity has no owner, clean up the operational data store (it's possible because owner controller
432             // might went down abruptly and didn't get a chance to clean up the operational data store.
433             if (!ownershipChange.getState().hasOwner()) {
434                 LOG.info("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
435                 cleanEntityOperationalData(ownershipChange.getEntity());
436             }
437             return;
438         }
439         //Connection detail need to be cached, irrespective of ownership result.
440         putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
441
442         if (ownershipChange.getState().isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
443             LOG.info("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
444                     ovsdbConnectionInstance.getConnectionInfo(), ovsdbConnectionInstance.getHasDeviceOwnership()
445                             ? SouthboundConstants.OwnershipStates.OWNER.getState()
446                             : SouthboundConstants.OwnershipStates.NONOWNER.getState());
447             return;
448         }
449
450         ovsdbConnectionInstance.setHasDeviceOwnership(ownershipChange.getState().isOwner());
451         // You were not an owner, but now you are
452         if (ownershipChange.getState().isOwner()) {
453             LOG.info("handleOwnershipChanged: *this* southbound plugin instance is an OWNER of the device {}",
454                     ovsdbConnectionInstance.getConnectionInfo());
455
456             //*this* instance of southbound plugin is owner of the device,
457             //so register for monitor callbacks
458             ovsdbConnectionInstance.registerCallbacks(instanceIdentifierCodec);
459
460             reconcileBridgeConfigurations(ovsdbConnectionInstance);
461         } else {
462             //You were owner of the device, but now you are not. With the current ownership
463             //grant mechanism, this scenario should not occur. Because this scenario will occur
464             //when this controller went down or switch flap the connection, but in both the case
465             //it will go through the re-registration process. We need to implement this condition
466             //when clustering service implement a ownership grant strategy which can revoke the
467             //device ownership for load balancing the devices across the instances.
468             //Once this condition occur, we should unregister the callback.
469             LOG.error("handleOwnershipChanged: *this* southbound plugin instance is no longer the owner of device {}."
470                     + "This should NOT happen.",
471                     ovsdbConnectionInstance.getNodeId().getValue());
472         }
473     }
474
475     private void cleanEntityOperationalData(final Entity entity) {
476
477         //Do explicit cleanup rather than using OvsdbNodeRemoveCommand, because there
478         // are chances that other controller instance went down abruptly and it does
479         // not clear manager entry, which OvsdbNodeRemoveCommand look for before cleanup.
480
481         @SuppressWarnings("unchecked")
482         final InstanceIdentifier<Node> nodeIid = (InstanceIdentifier<Node>) entity.getIdentifier();
483
484         txInvoker.invoke(transaction -> {
485             Optional<Node> ovsdbNodeOpt = SouthboundUtil.readNode(transaction, nodeIid);
486             if (ovsdbNodeOpt.isPresent()) {
487                 Node ovsdbNode = ovsdbNodeOpt.get();
488                 OvsdbNodeAugmentation nodeAugmentation = ovsdbNode.augmentation(OvsdbNodeAugmentation.class);
489                 if (nodeAugmentation != null) {
490                     if (nodeAugmentation.getManagedNodeEntry() != null) {
491                         for (ManagedNodeEntry managedNode : nodeAugmentation.getManagedNodeEntry()) {
492                             transaction.delete(
493                                     LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
494                         }
495                     } else {
496                         LOG.debug("{} had no managed nodes", ovsdbNode.getNodeId().getValue());
497                     }
498                 }
499                 transaction.delete(LogicalDatastoreType.OPERATIONAL, nodeIid);
500             }
501         });
502
503     }
504
505     private static OpenVSwitch getOpenVswitchTableEntry(final OvsdbConnectionInstance connectionInstance) {
506         final TypedDatabaseSchema dbSchema;
507         try {
508             dbSchema = connectionInstance.getSchema(OvsdbSchemaContants.DATABASE_NAME).get();
509         } catch (InterruptedException | ExecutionException e) {
510             LOG.warn("Not able to fetch schema for database {} from device {}",
511                     OvsdbSchemaContants.DATABASE_NAME,connectionInstance.getConnectionInfo(),e);
512             return null;
513         }
514
515         final GenericTableSchema openVSwitchSchema = dbSchema.getTableSchema(OpenVSwitch.class);
516         final Select<GenericTableSchema> selectOperation = op.select(openVSwitchSchema);
517         selectOperation.setColumns(new ArrayList<>(openVSwitchSchema.getColumns()));
518
519         List<Operation> operations = new ArrayList<>();
520         operations.add(selectOperation);
521         operations.add(op.comment("Fetching Open_VSwitch table rows"));
522         final List<OperationResult> results;
523         try {
524             results = connectionInstance.transact(dbSchema, operations).get();
525         } catch (InterruptedException | ExecutionException e) {
526             LOG.warn("Not able to fetch OpenVswitch table row from device {}", connectionInstance.getConnectionInfo(),
527                 e);
528             return null;
529         }
530
531         return results == null || results.isEmpty() ? null
532                 : dbSchema.getTypedRowWrapper(OpenVSwitch.class, results.get(0).getRows().get(0));
533     }
534
535     private Entity getEntityFromConnectionInstance(@NonNull final OvsdbConnectionInstance ovsdbConnectionInstance) {
536         InstanceIdentifier<Node> iid = ovsdbConnectionInstance.getInstanceIdentifier();
537         if (iid == null) {
538             /* Switch initiated connection won't have iid, till it gets OpenVSwitch
539              * table update but update callback is always registered after ownership
540              * is granted. So we are explicitly fetch the row here to get the iid.
541              */
542             OpenVSwitch openvswitchRow = getOpenVswitchTableEntry(ovsdbConnectionInstance);
543             iid = SouthboundMapper.getInstanceIdentifier(instanceIdentifierCodec, openvswitchRow);
544             LOG.info("InstanceIdentifier {} generated for device "
545                     + "connection {}",iid,ovsdbConnectionInstance.getConnectionInfo());
546             ovsdbConnectionInstance.setInstanceIdentifier(iid);
547         }
548         Entity deviceEntity = new Entity(ENTITY_TYPE, iid);
549         LOG.debug("Entity {} created for device connection {}",
550                 deviceEntity, ovsdbConnectionInstance.getConnectionInfo());
551         return deviceEntity;
552     }
553
554     private OvsdbConnectionInstance getConnectionInstanceFromEntity(final Entity entity) {
555         return entityConnectionMap.get(entity);
556     }
557
558     private void registerEntityForOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
559         putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(), ovsdbConnectionInstance);
560
561         Entity candidateEntity = getEntityFromConnectionInstance(ovsdbConnectionInstance);
562         if (entityConnectionMap.containsKey(candidateEntity)) {
563             LOG.error("Old connection still hanging for {}", candidateEntity);
564             disconnected(ovsdbConnectionInstance.getOvsdbClient());
565             //TODO do cleanup for old connection or stale check
566         }
567         nodeIdVsConnectionInstance.put((InstanceIdentifier<Node>) candidateEntity.getIdentifier(),
568                 ovsdbConnectionInstance);
569         entityConnectionMap.put(candidateEntity, ovsdbConnectionInstance);
570         ovsdbConnectionInstance.setConnectedEntity(candidateEntity);
571         try {
572             EntityOwnershipCandidateRegistration registration =
573                     entityOwnershipService.registerCandidate(candidateEntity);
574             ovsdbConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
575             LOG.info("OVSDB entity {} is registered for ownership.", candidateEntity);
576
577         } catch (CandidateAlreadyRegisteredException e) {
578             LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
579         }
580         //If entity already has owner, it won't get notification from EntityOwnershipService
581         java.util.Optional<EntityOwnershipState> ownershipStateOpt =
582                 entityOwnershipService.getOwnershipState(candidateEntity);
583         if (ownershipStateOpt.isPresent()) {
584             EntityOwnershipState ownershipState = ownershipStateOpt.get();
585             if (ownershipState == EntityOwnershipState.OWNED_BY_OTHER) {
586                 ovsdbConnectionInstance.setHasDeviceOwnership(false);
587             } else if (ownershipState == EntityOwnershipState.IS_OWNER) {
588                 ovsdbConnectionInstance.setHasDeviceOwnership(true);
589                 ovsdbConnectionInstance.registerCallbacks(instanceIdentifierCodec);
590             }
591         }
592     }
593
594     private void unregisterEntityForOwnership(final OvsdbConnectionInstance ovsdbConnectionInstance) {
595         ovsdbConnectionInstance.closeDeviceOwnershipCandidateRegistration();
596         entityConnectionMap.remove(ovsdbConnectionInstance.getConnectedEntity(), ovsdbConnectionInstance);
597     }
598
599     private void retryConnection(final InstanceIdentifier<Node> iid, final OvsdbNodeAugmentation ovsdbNode,
600                                  final ConnectionReconciliationTriggers trigger) {
601         final ReconciliationTask task = new ConnectionReconciliationTask(
602                 reconciliationManager,
603                 this,
604                 iid,
605                 ovsdbNode);
606
607         if (reconciliationManager.isEnqueued(task)) {
608             return;
609         }
610         switch (trigger) {
611             case ON_CONTROLLER_INITIATED_CONNECTION_FAILURE:
612                 reconciliationManager.enqueueForRetry(task);
613                 break;
614             case ON_DISCONNECT: {
615                 CheckedFuture<Optional<Node>, ReadFailedException> readNodeFuture;
616                 try (ReadOnlyTransaction tx = db.newReadOnlyTransaction()) {
617                     readNodeFuture = tx.read(LogicalDatastoreType.CONFIGURATION, iid);
618                 }
619                 Futures.addCallback(readNodeFuture, new FutureCallback<Optional<Node>>() {
620                     @Override
621                     public void onSuccess(final Optional<Node> node) {
622                         if (node.isPresent()) {
623                             LOG.info("Disconnected/Failed connection {} was controller initiated, attempting "
624                                     + "reconnection", ovsdbNode.getConnectionInfo());
625                             reconciliationManager.enqueue(task);
626
627                         } else {
628                             LOG.debug("Connection {} was switch initiated, no reconciliation is required",
629                                     iid.firstKeyOf(Node.class).getNodeId());
630                         }
631                     }
632
633                     @Override
634                     public void onFailure(final Throwable throwable) {
635                         LOG.warn("Read Config/DS for Node failed! {}", iid, throwable);
636                     }
637                 }, MoreExecutors.directExecutor());
638                 break;
639             }
640             default:
641                 break;
642         }
643     }
644
645     private void reconcileBridgeConfigurations(final OvsdbConnectionInstance client) {
646         final InstanceIdentifier<Node> nodeIid = client.getInstanceIdentifier();
647         final ReconciliationTask task = new BridgeConfigReconciliationTask(
648                 reconciliationManager, OvsdbConnectionManager.this, nodeIid, client, instanceIdentifierCodec);
649
650         reconciliationManager.enqueue(task);
651     }
652
653     private static class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
654         private final OvsdbConnectionManager cm;
655         private final EntityOwnershipListenerRegistration listenerRegistration;
656
657         OvsdbDeviceEntityOwnershipListener(final OvsdbConnectionManager cm,
658                 final EntityOwnershipService entityOwnershipService) {
659             this.cm = cm;
660             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
661         }
662
663         public void close() {
664             listenerRegistration.close();
665         }
666
667         @Override
668         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
669             cm.handleOwnershipChanged(ownershipChange);
670         }
671     }
672
673     private enum ConnectionReconciliationTriggers {
674         /*
675         Reconciliation trigger for scenario where controller's attempt
676         to connect to switch fails on config data store notification
677         */
678         ON_CONTROLLER_INITIATED_CONNECTION_FAILURE,
679
680         /*
681         Reconciliation trigger for the scenario where controller
682         initiated connection disconnects.
683         */
684         ON_DISCONNECT
685     }
686 }