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