Add Interface Table Columns and Version Info
[ovsdb.git] / schemas / Open_vSwitch / src / test / java / org / opendaylight / ovsdb / schema / openvswitch / TypedVSwitchdSchemaIT.java
1 /*
2  * Copyright (C) 2014 Red Hat, Inc.
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  * Authors : Madhu Venugopal
9  */
10 package org.opendaylight.ovsdb.schema.openvswitch;
11
12 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
13
14 import java.io.IOException;
15 import java.lang.reflect.InvocationTargetException;
16 import java.util.HashMap;
17 import java.math.BigInteger;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.ExecutorService;
22 import java.util.concurrent.Executors;
23
24 import com.google.common.collect.ImmutableSet;
25 import junit.framework.Assert;
26
27 import org.junit.After;
28 import org.junit.Before;
29 import org.junit.Test;
30 import org.opendaylight.ovsdb.lib.MonitorCallBack;
31 import org.opendaylight.ovsdb.lib.MonitorHandle;
32 import org.opendaylight.ovsdb.lib.OvsDBClientImpl;
33 import org.opendaylight.ovsdb.lib.message.MonitorRequest;
34 import org.opendaylight.ovsdb.lib.message.MonitorRequestBuilder;
35 import org.opendaylight.ovsdb.lib.message.MonitorSelect;
36 import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
37 import org.opendaylight.ovsdb.lib.message.TableUpdate;
38 import org.opendaylight.ovsdb.lib.message.TableUpdates;
39 import org.opendaylight.ovsdb.lib.message.UpdateNotification;
40 import org.opendaylight.ovsdb.lib.notation.Mutator;
41 import org.opendaylight.ovsdb.lib.notation.Row;
42 import org.opendaylight.ovsdb.lib.notation.UUID;
43 import org.opendaylight.ovsdb.lib.operations.OperationResult;
44 import org.opendaylight.ovsdb.lib.operations.TransactionBuilder;
45 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
46 import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 import com.google.common.collect.ImmutableMap;
51 import com.google.common.collect.Lists;
52 import com.google.common.collect.Sets;
53 import com.google.common.util.concurrent.ListenableFuture;
54
55 public class TypedVSwitchdSchemaIT extends OvsdbTestBase {
56
57     Logger logger = LoggerFactory.getLogger(TypedVSwitchdSchemaIT.class);
58     OvsDBClientImpl ovs;
59     DatabaseSchema dbSchema = null;
60     static String testBridgeName = "br_test";
61     static UUID testBridgeUuid = null;
62
63     @Test
64     public void testTypedBridgeOperations() throws IOException, InterruptedException, ExecutionException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
65         this.monitorTables();
66         this.createTypedBridge();
67         this.createTypedController();
68         this.testCreateTypedPortandInterface();
69     }
70
71     private void createTypedBridge() throws IOException, InterruptedException, ExecutionException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
72         Bridge bridge = ovs.createTypedRowWrapper(Bridge.class);
73         bridge.setName(testBridgeName);
74         bridge.setStatus(ImmutableMap.of("key","value"));
75         bridge.setFloodVlans(Sets.newHashSet(34));
76
77         OpenVSwitch openVSwitch = ovs.createTypedRowWrapper(OpenVSwitch.class);
78         openVSwitch.setBridges(Sets.newHashSet(new UUID(testBridgeName)));
79
80         int insertOperationIndex = 0;
81
82         TransactionBuilder transactionBuilder = ovs.transactBuilder()
83                 .add(op.insert(bridge.getSchema())
84                         .withId(testBridgeName)
85                         .value(bridge.getNameColumn()))
86                 .add(op.update(bridge.getSchema())
87                         .set(bridge.getStatusColumn())
88                         .set(bridge.getFloodVlansColumn())
89                         .where(bridge.getNameColumn().getSchema().opEqual(bridge.getName()))
90                         .and(bridge.getNameColumn().getSchema().opEqual(bridge.getName())).build())
91                 .add(op.mutate(openVSwitch.getSchema())
92                         .addMutation(openVSwitch.getBridgesColumn().getSchema(), Mutator.INSERT,
93                                      openVSwitch.getBridgesColumn().getData()));
94
95         ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
96         List<OperationResult> operationResults = results.get();
97         Assert.assertFalse(operationResults.isEmpty());
98         // Check if Results matches the number of operations in transaction
99         Assert.assertEquals(transactionBuilder.getOperations().size(), operationResults.size());
100         System.out.println("Insert & Update operation results = " + operationResults);
101         for (OperationResult result : operationResults) {
102             Assert.assertNull(result.getError());
103         }
104         testBridgeUuid = operationResults.get(insertOperationIndex).getUuid();
105
106         Row bridgeRow = tableCache.get(bridge.getSchema().getName()).get(testBridgeUuid);
107         Bridge monitoredBridge = ovs.getTypedRowWrapper(Bridge.class, bridgeRow);
108         Assert.assertEquals(monitoredBridge.getNameColumn().getData(), bridge.getNameColumn().getData());
109         Assert.assertNotNull(monitoredBridge.getVersion());
110         Assert.assertNotNull(this.getOpenVSwitchTableUuid());
111     }
112
113     private void createTypedController() throws IOException, InterruptedException, ExecutionException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
114         Controller controller1 = ovs.createTypedRowWrapper(Controller.class);
115         controller1.setTarget("tcp:1.1.1.1:6640");
116         Controller controller2 = ovs.createTypedRowWrapper(Controller.class);
117         controller2.setTarget("tcp:2.2.2.2:6640");
118
119         Bridge bridge = ovs.getTypedRowWrapper(Bridge.class, null);
120
121         String transactionUuidStr = "controller";
122         TransactionBuilder transactionBuilder = ovs.transactBuilder()
123                 .add(op.insert(controller1.getSchema())
124                         .withId(transactionUuidStr)
125                         .value(controller1.getTargetColumn()))
126                 .add(op.mutate(bridge.getSchema())
127                         .addMutation(bridge.getControllerColumn().getSchema(), Mutator.INSERT,
128                                      Sets.newHashSet(new UUID(transactionUuidStr)))
129                         .where(bridge.getNameColumn().getSchema().opEqual(testBridgeName))
130                         .build());
131
132         ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
133         List<OperationResult> operationResults = results.get();
134         Assert.assertFalse(operationResults.isEmpty());
135         // Check if Results matches the number of operations in transaction
136         Assert.assertEquals(transactionBuilder.getOperations().size(), operationResults.size());
137         System.out.println("Insert & Mutate operation results for controller1 = " + operationResults);
138         // Check for any errors
139         for (OperationResult result : operationResults) {
140             Assert.assertNull(result.getError());
141         }
142
143         Row bridgeRow = tableCache.get(bridge.getSchema().getName()).get(testBridgeUuid);
144         Bridge monitoredBridge = ovs.getTypedRowWrapper(Bridge.class, bridgeRow);
145         Assert.assertEquals(1, monitoredBridge.getControllerColumn().getData().size());
146
147         transactionBuilder = ovs.transactBuilder()
148                 .add(op.insert(controller2.getSchema())
149                         .withId(transactionUuidStr)
150                         .value(controller2.getTargetColumn()))
151                 .add(op.mutate(bridge.getSchema())
152                         .addMutation(bridge.getControllerColumn().getSchema(), Mutator.INSERT,
153                                 Sets.newHashSet(new UUID(transactionUuidStr)))
154                         .where(bridge.getNameColumn().getSchema().opEqual(testBridgeName))
155                         .build());
156
157         results = transactionBuilder.execute();
158         operationResults = results.get();
159         Assert.assertFalse(operationResults.isEmpty());
160         // Check if Results matches the number of operations in transaction
161         Assert.assertEquals(transactionBuilder.getOperations().size(), operationResults.size());
162         System.out.println("Insert & Mutate operation results for controller2 = " + operationResults);
163         // Check for any errors
164         for (OperationResult result : operationResults) {
165             Assert.assertNull(result.getError());
166         }
167
168         bridgeRow = tableCache.get(bridge.getSchema().getName()).get(testBridgeUuid);
169         monitoredBridge = ovs.getTypedRowWrapper(Bridge.class, bridgeRow);
170         Assert.assertEquals(2, monitoredBridge.getControllerColumn().getData().size());
171     }
172
173     private void testCreateTypedPortandInterface() throws InterruptedException, ExecutionException{
174         String portUuidStr = "testPort";
175         String intfUuidStr = "testIntf";
176         Port port = ovs.createTypedRowWrapper(Port.class);
177         port.setName("testPort");
178         port.setTag(ImmutableSet.of(BigInteger.ONE));
179         port.setMac(ImmutableSet.of("00:00:00:00:00:01"));
180         port.setInterfaces(ImmutableSet.of(new UUID(intfUuidStr)));
181
182         Interface intf = ovs.createTypedRowWrapper(Interface.class);
183         intf.setName(port.getNameColumn().getData());
184         intf.setExternalIds(ImmutableMap.of("vm-id", "12345abcedf78910"));
185
186         Bridge bridge = ovs.getTypedRowWrapper(Bridge.class, null);
187         TransactionBuilder transactionBuilder = ovs.transactBuilder()
188                 .add(op.insert(port.getSchema())
189                         .withId(portUuidStr)
190                         .value(port.getNameColumn())
191                         .value(port.getMacColumn()))
192                 .add(op.insert(intf.getSchema())
193                         .withId(intfUuidStr)
194                         .value(intf.getNameColumn()))
195                 .add(op.update(port.getSchema())
196                         .set(port.getTagColumn())
197                         .set(port.getMacColumn())
198                         .set(port.getInterfacesColumn())
199                         .where(port.getNameColumn().getSchema().opEqual(port.getName()))
200                         .build())
201                 .add(op.update(intf.getSchema())
202                         .set(intf.getExternalIdsColumn())
203                         .where(intf.getNameColumn().getSchema().opEqual(intf.getName()))
204                         .build())
205                 .add(op.mutate(bridge.getSchema())
206                         .addMutation(bridge.getPortsColumn().getSchema(), Mutator.INSERT, Sets.newHashSet(new UUID(portUuidStr)))
207                         .where(bridge.getNameColumn().getSchema().opEqual(testBridgeName))
208                         .build());
209         ListenableFuture<List<OperationResult>> results = transactionBuilder.execute();
210         List<OperationResult> operationResults = results.get();
211         Assert.assertFalse(operationResults.isEmpty());
212         // Check if Results matches the number of operations in transaction
213         Assert.assertEquals(transactionBuilder.getOperations().size(), operationResults.size());
214         System.out.println("Insert & Mutate operation results for Port and Interface = " + operationResults);
215     }
216
217     public void testGetDBs() throws ExecutionException, InterruptedException {
218         ListenableFuture<List<String>> databases = ovs.getDatabases();
219         List<String> dbNames = databases.get();
220         Assert.assertNotNull(dbNames);
221         boolean hasOpenVswitchSchema = false;
222         for(String dbName : dbNames) {
223            if (dbName.equals(OPEN_VSWITCH_SCHEMA)) {
224                 hasOpenVswitchSchema = true;
225                 break;
226            }
227         }
228         Assert.assertTrue(OPEN_VSWITCH_SCHEMA+" schema is not supported by the switch", hasOpenVswitchSchema);
229     }
230
231     private UUID getOpenVSwitchTableUuid() {
232         OpenVSwitch openVSwitch = ovs.getTypedRowWrapper(OpenVSwitch.class, null);
233         Map<UUID, Row> ovsTable = tableCache.get(openVSwitch.getSchema().getName());
234         if (ovsTable != null) {
235             if (ovsTable.keySet().size() >= 1) {
236                 return (UUID)ovsTable.keySet().toArray()[0];
237             }
238         }
239         return null;
240     }
241
242     public void monitorTables() throws ExecutionException, InterruptedException, IOException {
243         Assert.assertNotNull(dbSchema);
244         Bridge bridge = ovs.createTypedRowWrapper(Bridge.class);
245         OpenVSwitch openVSwitch = ovs.createTypedRowWrapper(OpenVSwitch.class);
246
247         List<MonitorRequest<GenericTableSchema>> monitorRequests = Lists.newArrayList();
248         MonitorRequestBuilder<GenericTableSchema> bridgeBuilder = MonitorRequestBuilder.builder(bridge.getSchema());
249         MonitorRequestBuilder<GenericTableSchema> ovsTableBuilder = MonitorRequestBuilder.builder(openVSwitch.getSchema());
250         monitorRequests.add(bridgeBuilder.with(new MonitorSelect(true, true, true, true)).build());
251         monitorRequests.add(ovsTableBuilder.with(new MonitorSelect(true, true, true, true)).build());
252
253         MonitorHandle monitor = ovs.monitor(dbSchema, monitorRequests, new UpdateMonitor());
254         Assert.assertNotNull(monitor);
255     }
256
257     static Map<String, Map<UUID, Row>> tableCache = new HashMap<String, Map<UUID, Row>>();
258     private static class UpdateMonitor implements MonitorCallBack {
259         @Override
260         public void update(TableUpdates result) {
261             for (String tableName : result.getUpdates().keySet()) {
262                 Map<UUID, Row> tUpdate = tableCache.get(tableName);
263                 TableUpdate update = result.getUpdates().get(tableName);
264                 if (update.getNew() != null) {
265                     if (tUpdate == null) {
266                         tUpdate = new HashMap<UUID, Row>();
267                         tableCache.put(tableName, tUpdate);
268                     }
269                     tUpdate.put(update.getUuid(), update.getNew());
270                 } else {
271                     tUpdate.remove(update.getUuid());
272                 }
273             }
274         }
275
276         @Override
277         public void exception(Throwable t) {
278             System.out.println("Exception t = " + t);
279         }
280     }
281
282     @Before
283     public  void setUp() throws IOException, ExecutionException, InterruptedException {
284         if (ovs != null) {
285             return;
286         }
287         OvsdbRPC rpc = getTestConnection();
288         if (rpc == null) {
289             System.out.println("Unable to Establish Test Connection");
290         }
291         ExecutorService executorService = Executors.newFixedThreadPool(3);
292         ovs = new OvsDBClientImpl(rpc, executorService);
293         testGetDBs();
294         dbSchema = ovs.getSchema(OPEN_VSWITCH_SCHEMA, true).get();
295     }
296
297     @After
298     public void tearDown() throws InterruptedException, ExecutionException {
299         Bridge bridge = ovs.getTypedRowWrapper(Bridge.class, null);
300         OpenVSwitch openVSwitch = ovs.getTypedRowWrapper(OpenVSwitch.class, null);
301
302         ListenableFuture<List<OperationResult>> results = ovs.transactBuilder()
303                 .add(op.delete(bridge.getSchema())
304                         .where(bridge.getNameColumn().getSchema().opEqual(testBridgeName))
305                         .build())
306                 .add(op.mutate(openVSwitch.getSchema())
307                         .addMutation(openVSwitch.getBridgesColumn().getSchema(), Mutator.DELETE, Sets.newHashSet(testBridgeUuid)))
308                 .add(op.commit(true))
309                 .execute();
310
311         List<OperationResult> operationResults = results.get();
312         System.out.println("Delete operation results = " + operationResults);
313         tableCache = new HashMap<String, Map<UUID, Row>>();
314     }
315
316     @Override
317     public void update(Object node, UpdateNotification upadateNotification) {
318         // TODO Auto-generated method stub
319
320     }
321     @Override
322     public void locked(Object node, List<String> ids) {
323         // TODO Auto-generated method stub
324
325     }
326     @Override
327     public void stolen(Object node, List<String> ids) {
328         // TODO Auto-generated method stub
329
330     }
331 }