Added device transaction log cli
[ovsdb.git] / hwvtepsouthbound / hwvtepsouthbound-impl / src / main / java / org / opendaylight / ovsdb / hwvtepsouthbound / HwvtepConnectionInstance.java
1 /*
2  * Copyright (c) 2015, 2017 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 java.util.ArrayList;
12 import java.util.HashMap;
13 import java.util.HashSet;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Set;
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.Executors;
19 import java.util.concurrent.ScheduledExecutorService;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.atomic.AtomicBoolean;
22
23 import javax.annotation.Nonnull;
24
25 import com.google.common.util.concurrent.FutureCallback;
26 import com.google.common.util.concurrent.Futures;
27 import com.google.common.util.concurrent.SettableFuture;
28 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
29 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
30 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
31 import org.opendaylight.ovsdb.hwvtepsouthbound.transact.TransactCommand;
32 import org.opendaylight.ovsdb.hwvtepsouthbound.transact.TransactInvoker;
33 import org.opendaylight.ovsdb.hwvtepsouthbound.transact.TransactInvokerImpl;
34 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvoker;
35 import org.opendaylight.ovsdb.lib.LockAquisitionCallback;
36 import org.opendaylight.ovsdb.lib.LockStolenCallback;
37 import org.opendaylight.ovsdb.lib.MonitorCallBack;
38 import org.opendaylight.ovsdb.lib.MonitorHandle;
39 import org.opendaylight.ovsdb.lib.OvsdbClient;
40 import org.opendaylight.ovsdb.lib.OvsdbConnectionInfo;
41 import org.opendaylight.ovsdb.lib.message.MonitorRequest;
42 import org.opendaylight.ovsdb.lib.message.MonitorRequestBuilder;
43 import org.opendaylight.ovsdb.lib.message.MonitorSelect;
44 import org.opendaylight.ovsdb.lib.message.TableUpdates;
45 import org.opendaylight.ovsdb.lib.notation.Row;
46 import org.opendaylight.ovsdb.lib.operations.Operation;
47 import org.opendaylight.ovsdb.lib.operations.OperationResult;
48 import org.opendaylight.ovsdb.lib.operations.TransactionBuilder;
49 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
50 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
51 import org.opendaylight.ovsdb.lib.schema.TableSchema;
52 import org.opendaylight.ovsdb.lib.schema.typed.TypedBaseTable;
53 import org.opendaylight.ovsdb.utils.mdsal.utils.TransactionHistory;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.ConnectionInfo;
56 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
57 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
58 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
59 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 import com.google.common.util.concurrent.ListenableFuture;
64
65 public class HwvtepConnectionInstance {
66     private static final Logger LOG = LoggerFactory.getLogger(HwvtepConnectionInstance.class);
67     private ConnectionInfo connectionInfo;
68     private OvsdbClient client;
69     private final HwvtepTableReader hwvtepTableReader;
70     private InstanceIdentifier<Node> instanceIdentifier;
71     private TransactionInvoker txInvoker;
72     private Map<DatabaseSchema,TransactInvoker> transactInvokers;
73     private MonitorCallBack callback;
74     private volatile boolean hasDeviceOwnership = false;
75     private Entity connectedEntity;
76     private EntityOwnershipCandidateRegistration deviceOwnershipCandidateRegistration;
77     private HwvtepGlobalAugmentation initialCreatedData = null;
78     private HwvtepDeviceInfo deviceInfo;
79     private DataBroker dataBroker;
80     private final HwvtepConnectionManager hwvtepConnectionManager;
81     private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
82     private final SettableFuture<Boolean> reconciliationFt = SettableFuture.create();
83     private final AtomicBoolean firstUpdateTriggered = new AtomicBoolean(false);
84     private TransactionHistory controllerTxHistory;
85     private TransactionHistory deviceUpdateHistory;
86
87     HwvtepConnectionInstance (HwvtepConnectionManager hwvtepConnectionManager, ConnectionInfo key, OvsdbClient client,
88                               InstanceIdentifier<Node> iid, TransactionInvoker txInvoker, DataBroker dataBroker) {
89         this.hwvtepConnectionManager = hwvtepConnectionManager;
90         this.connectionInfo = key;
91         this.client = client;
92         this.instanceIdentifier = iid;
93         this.txInvoker = txInvoker;
94         this.deviceInfo = new HwvtepDeviceInfo(this);
95         this.dataBroker = dataBroker;
96         this.hwvtepTableReader = new HwvtepTableReader(this);
97     }
98
99     public void transact(final TransactCommand command) {
100         String nodeId = getNodeId().getValue();
101         boolean firstUpdate = firstUpdateTriggered.compareAndSet(false, true);
102         if (reconciliationFt.isDone()) {
103             transact(command, false);
104         } else {
105             LOG.info("Job waiting for reconciliation {}", nodeId);
106             Futures.addCallback(reconciliationFt, new FutureCallback<Boolean>() {
107                 @Override
108                 public void onSuccess(Boolean aBoolean) {
109                     LOG.info("Running the job waiting for reconciliation {}", nodeId);
110                     transact(command, false);
111                 }
112
113                 @Override
114                 public void onFailure(Throwable throwable) {
115                     LOG.info("Running the job waiting for reconciliation {}", nodeId);
116                     transact(command, false);
117                 }
118             });
119             if (firstUpdate) {
120                 LOG.info("Scheduling the reconciliation timeout task {}", nodeId);
121                 scheduledExecutorService.schedule( () -> reconciliationFt.set(Boolean.TRUE),
122                         HwvtepSouthboundConstants.CONFIG_NODE_UPDATE_MAX_DELAY_MS, TimeUnit.MILLISECONDS);
123             }
124         }
125     }
126
127     public synchronized void transact(TransactCommand command, boolean reconcile) {
128         try {
129             for (TransactInvoker transactInvoker : transactInvokers.values()) {
130                 transactInvoker.invoke(command);
131             }
132         } finally {
133             if (reconcile) {
134                 reconciliationFt.set(Boolean.TRUE);
135             }
136         }
137     }
138
139     public void registerCallbacks() {
140         if ( this.callback == null) {
141             if(this.initialCreatedData != null) {
142                 this.updateConnectionAttributes();
143             }
144
145             try {
146                 String database = HwvtepSchemaConstants.HARDWARE_VTEP;
147                 DatabaseSchema dbSchema = getSchema(database).get();
148                 if (dbSchema != null) {
149                     LOG.info("Monitoring database: {}", database);
150                     callback = new HwvtepMonitorCallback(this, txInvoker);
151                     monitorAllTables(database, dbSchema);
152                 } else {
153                     LOG.info("No database {} found on {}", database, connectionInfo);
154                 }
155             } catch (InterruptedException | ExecutionException e) {
156                 LOG.warn("Exception attempting to registerCallbacks {}: ", connectionInfo, e);
157             }
158         }
159     }
160
161     public void createTransactInvokers() {
162         if (transactInvokers == null) {
163             try {
164                 transactInvokers = new HashMap<>();
165                 DatabaseSchema dbSchema = getSchema(HwvtepSchemaConstants.HARDWARE_VTEP).get();
166                 if(dbSchema != null) {
167                     transactInvokers.put(dbSchema, new TransactInvokerImpl(this,dbSchema));
168                 }
169             } catch (InterruptedException | ExecutionException e) {
170                 LOG.warn("Exception attempting to createTransactionInvokers {}", connectionInfo, e);
171             }
172         }
173     }
174
175     private void monitorAllTables(String database, DatabaseSchema dbSchema) {
176         Set<String> tables = dbSchema.getTables();
177         if (tables != null) {
178             List<MonitorRequest> monitorRequests = new ArrayList<>();
179             for (String tableName : tables) {
180                 if (!HwvtepSouthboundConstants.SKIP_HWVTEP_TABLE.containsKey(tableName)) {
181                     LOG.info("HwvtepSouthbound monitoring Hwvtep schema table {}", tableName);
182                     GenericTableSchema tableSchema = dbSchema.table(tableName, GenericTableSchema.class);
183                     Set<String> columns = new HashSet<>(tableSchema.getColumns());
184                     List<String> skipColumns = HwvtepSouthboundConstants.SKIP_COLUMN_FROM_HWVTEP_TABLE.get(tableName);
185                     skipColumns = skipColumns == null ? new ArrayList<>() : new ArrayList<>(skipColumns);
186                     skipColumns.add(HwvtepSouthboundConstants.VERSION_COLUMN);
187                     if (skipColumns != null) {
188                         LOG.info("HwvtepSouthbound NOT monitoring columns {} in table {}", skipColumns, tableName);
189                         columns.removeAll(skipColumns);
190                     }
191                     monitorRequests.add(new MonitorRequestBuilder<>(tableSchema)
192                             .addColumns(columns)
193                             .with(new MonitorSelect(true, true, true, true)).build());
194                 }
195             }
196             this.callback.update(monitor(dbSchema, monitorRequests, callback), dbSchema);
197         } else {
198             LOG.warn("No tables for schema {} for database {} for key {}",dbSchema,database,connectionInfo);
199         }
200     }
201
202     private void updateConnectionAttributes() {
203         LOG.debug("Update attributes of ovsdb node ip: {} port: {}",
204                     this.initialCreatedData.getConnectionInfo().getRemoteIp(),
205                     this.initialCreatedData.getConnectionInfo().getRemotePort());
206         /*
207          * TODO: Do we have anything to update?
208          * Hwvtep doesn't have other_config or external_ids like
209          * Open_vSwitch. What else will be needed?
210          */
211     }
212
213     public DataBroker getDataBroker() {
214         return dataBroker;
215     }
216
217     public ListenableFuture<List<String>> getDatabases() {
218         return client.getDatabases();
219     }
220
221     public ListenableFuture<DatabaseSchema> getSchema(String database) {
222         return client.getSchema(database);
223     }
224
225     public TransactionBuilder transactBuilder(DatabaseSchema dbSchema) {
226         return client.transactBuilder(dbSchema);
227     }
228
229     public ListenableFuture<List<OperationResult>> transact(DatabaseSchema dbSchema, List<Operation> operations) {
230         return client.transact(dbSchema, operations);
231     }
232
233     public <E extends TableSchema<E>> TableUpdates monitor(DatabaseSchema schema,
234                     List<MonitorRequest> monitorRequests, MonitorCallBack callback) {
235         return client.monitor(schema, monitorRequests, callback);
236     }
237
238     public <E extends TableSchema<E>> TableUpdates monitor(DatabaseSchema schema,
239                     List<MonitorRequest> monitorRequests, MonitorHandle monitorHandle, MonitorCallBack callback) {
240         return null;
241     }
242
243     public void cancelMonitor(MonitorHandle handler) {
244         client.cancelMonitor(handler);
245     }
246
247     public void lock(String lockId, LockAquisitionCallback lockedCallBack, LockStolenCallback stolenCallback) {
248         client.lock(lockId, lockedCallBack, stolenCallback);
249     }
250
251     public ListenableFuture<Boolean> steal(String lockId) {
252         return client.steal(lockId);
253     }
254
255     public ListenableFuture<Boolean> unLock(String lockId) {
256         return client.unLock(lockId);
257     }
258
259     public OvsdbConnectionInfo getConnectionInfo() {
260         return client.getConnectionInfo();
261     }
262
263     public boolean isActive() {
264         return client.isActive();
265     }
266
267     public void disconnect() {
268         client.disconnect();
269     }
270
271     public DatabaseSchema getDatabaseSchema(String dbName) {
272         return client.getDatabaseSchema(dbName);
273     }
274
275     public <T extends TypedBaseTable<?>> T createTypedRowWrapper(Class<T> klazz) {
276         return client.createTypedRowWrapper(klazz);
277     }
278
279     public <T extends TypedBaseTable<?>> T createTypedRowWrapper(DatabaseSchema dbSchema, Class<T> klazz) {
280         return client.createTypedRowWrapper(dbSchema, klazz);
281     }
282
283     public <T extends TypedBaseTable<?>> T getTypedRowWrapper(Class<T> klazz, Row<GenericTableSchema> row) {
284         return client.getTypedRowWrapper(klazz, row);
285     }
286
287     public ConnectionInfo getMDConnectionInfo() {
288         return connectionInfo;
289     }
290
291     public void setMDConnectionInfo(ConnectionInfo key) {
292         this.connectionInfo = key;
293     }
294
295     public InstanceIdentifier<Node> getInstanceIdentifier() {
296         return instanceIdentifier;
297     }
298
299     public NodeKey getNodeKey() {
300         //TODO: What is the alternative here?
301         return getInstanceIdentifier().firstKeyOf(Node.class);
302     }
303
304     public NodeId getNodeId() {
305         return getNodeKey().getNodeId();
306     }
307
308     public void setInstanceIdentifier(InstanceIdentifier<Node> iid) {
309         this.instanceIdentifier = iid;
310         hwvtepConnectionManager.putConnectionInstance(instanceIdentifier, this);
311     }
312
313     public Entity getConnectedEntity() {
314         return this.connectedEntity;
315     }
316
317     public void setConnectedEntity(Entity entity ) {
318         this.connectedEntity = entity;
319     }
320
321     public Boolean hasOvsdbClient(OvsdbClient otherClient) {
322         return client.equals(otherClient);
323     }
324
325     public Boolean getHasDeviceOwnership() {
326         return hasDeviceOwnership;
327     }
328
329     public void setHasDeviceOwnership(Boolean hasDeviceOwnership) {
330         if (hasDeviceOwnership != null) {
331             this.hasDeviceOwnership = hasDeviceOwnership;
332         }
333     }
334
335     public void setDeviceOwnershipCandidateRegistration(@Nonnull EntityOwnershipCandidateRegistration registration) {
336         this.deviceOwnershipCandidateRegistration = registration;
337     }
338
339     public void closeDeviceOwnershipCandidateRegistration() {
340         if (deviceOwnershipCandidateRegistration != null) {
341             this.deviceOwnershipCandidateRegistration.close();
342             setHasDeviceOwnership(Boolean.FALSE);
343         }
344     }
345
346     public void setHwvtepGlobalAugmentation(HwvtepGlobalAugmentation hwvtepGlobalData) {
347         this.initialCreatedData = hwvtepGlobalData;
348     }
349
350     public HwvtepGlobalAugmentation getHwvtepGlobalAugmentation() {
351         return this.initialCreatedData;
352     }
353     public HwvtepDeviceInfo getDeviceInfo() {
354         return this.deviceInfo;
355     }
356
357     public OvsdbClient getOvsdbClient() {
358         return client;
359     }
360
361     public HwvtepTableReader getHwvtepTableReader() {
362         return hwvtepTableReader;
363     }
364
365     public void refreshOperNode() throws ExecutionException, InterruptedException {
366         TableUpdates tableUpdates = hwvtepTableReader.readAllTables();
367         callback.update(tableUpdates, getDatabaseSchema(HwvtepSchemaConstants.HARDWARE_VTEP));
368     }
369
370     public MonitorCallBack getCallback() {
371         return callback;
372     }
373
374     public void setCallback(MonitorCallBack callback) {
375         this.callback = callback;
376     }
377
378     public TransactionHistory getControllerTxHistory() {
379         return controllerTxHistory;
380     }
381
382     public void setControllerTxHistory(TransactionHistory controllerTxLog) {
383         deviceInfo.setControllerTxHistory(controllerTxLog);
384         this.controllerTxHistory = controllerTxLog;
385     }
386
387     public TransactionHistory getDeviceUpdateHistory() {
388         return deviceUpdateHistory;
389     }
390
391     public void setDeviceUpdateHistory(TransactionHistory deviceUpdateLog) {
392         deviceInfo.setDeviceUpdateHistory(deviceUpdateLog);
393         this.deviceUpdateHistory = deviceUpdateLog;
394     }
395 }