Migrate from adsal Node to mdsal Node
[ovsdb.git] / integrationtest / src / test / java / org / opendaylight / ovsdb / integrationtest / northbound / OvsdbNorthboundV2IT.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 : Dave Tucker
9  */
10
11 package org.opendaylight.ovsdb.integrationtest.northbound;
12
13 import static org.junit.Assert.assertEquals;
14 import static org.junit.Assert.assertFalse;
15 import static org.junit.Assert.assertNotNull;
16 import static org.junit.Assert.assertTrue;
17 import static org.junit.Assert.fail;
18 import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
19 import static org.ops4j.pax.exam.CoreOptions.options;
20 import static org.ops4j.pax.exam.CoreOptions.propagateSystemProperty;
21 import static org.ops4j.pax.exam.CoreOptions.systemProperty;
22
23 import java.io.FileNotFoundException;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.inject.Inject;
30
31 import org.junit.Before;
32 import org.junit.Test;
33 import org.junit.runner.RunWith;
34 import org.junit.runners.Parameterized;
35 import org.opendaylight.controller.sal.core.Node;
36 import org.opendaylight.controller.usermanager.IUserManager;
37 import org.opendaylight.ovsdb.integrationtest.ConfigurationBundles;
38 import org.opendaylight.ovsdb.integrationtest.CompatOvsdbIntegrationTestBase;
39 import org.ops4j.pax.exam.Configuration;
40 import org.ops4j.pax.exam.Option;
41 import org.ops4j.pax.exam.junit.PaxExamParameterized;
42 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
43 import org.ops4j.pax.exam.spi.reactors.PerClass;
44 import org.ops4j.pax.exam.util.PathUtils;
45 import org.osgi.framework.Bundle;
46 import org.osgi.framework.BundleContext;
47 import org.osgi.framework.ServiceReference;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.yaml.snakeyaml.Yaml;
51
52 import com.fasterxml.jackson.databind.JsonNode;
53 import com.fasterxml.jackson.databind.ObjectMapper;
54 import com.google.common.collect.Lists;
55 import com.sun.jersey.api.client.Client;
56 import com.sun.jersey.api.client.ClientResponse;
57 import com.sun.jersey.api.client.WebResource;
58 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
59
60 @RunWith(PaxExamParameterized.class)
61 @ExamReactorStrategy(PerClass.class)
62 public class OvsdbNorthboundV2IT extends CompatOvsdbIntegrationTestBase {
63
64     private Logger log = LoggerFactory.getLogger(OvsdbNorthboundV2IT.class);
65     public static final String USERNAME = "admin";
66     public static final String PASSWORD = "admin";
67     public static final String BASE_URI = "http://localhost:8888";
68     public static final String MEDIA_TYPE_JSON = "application/json";
69     public static final String NODE_ID_REPLACEMENT_PATTERN = "${node}";
70     public static final String UUID_REPLACEMENT_PATTERN = "${uuid}";
71     public static final String BRIDGE_UUID_REPLACEMENT_PATTERN = "${bridge_uuid}";
72     public static final String PORT_UUID_REPLACEMENT_PATTERN = "${port_uuid}";
73     public static final String QOS_UUID_REPLACEMENT_PATTERN = "${qos_uuid}";
74     public static final String OVS_UUID_REPLACEMENT_PATTERN = "${ovs_uuid}";
75
76     @Inject
77     private BundleContext bc;
78     private Node node = null;
79     private IUserManager userManager;
80
81     @Parameterized.Parameters(name = "ApiTest{index}:{0}")
82     public static List<Object[]> getData() throws FileNotFoundException {
83         ClassLoader classloader = OvsdbNorthboundV2IT.class.getClassLoader();
84         InputStream input = classloader.getResourceAsStream("northbound.yaml");
85         Yaml yaml = new Yaml();
86         List<Map<String, Object>> object = (List<Map<String, Object>>) yaml.load(input);
87         List<Object[]> parameters = Lists.newArrayList();
88
89         for (Map<String, Object> o : object){
90             Object[] l = o.values().toArray();
91             parameters.add(l);
92             break;
93         }
94
95         return parameters;
96
97     }
98
99     private String fTestCase;
100     private String fOperation;
101     private String fPath;
102     private String fJson;
103     private int fExpectedStatusCode;
104
105     public OvsdbNorthboundV2IT (String testCase, String operation, String path, String json, int expectedStatusCode){
106         fTestCase = testCase;
107         fOperation = operation;
108         fPath = path;
109         fJson = json;
110         fExpectedStatusCode = expectedStatusCode;
111     }
112
113     @Test
114     public void testApi() {
115         System.out.println("Running " + fTestCase + "...\n");
116
117         Client client = Client.create();
118         client.addFilter(new HTTPBasicAuthFilter(USERNAME , PASSWORD));
119         String uri = BASE_URI + fPath;
120         WebResource webResource = client.resource(expand(uri));
121         ClientResponse response = null;
122
123         switch (fOperation) {
124             case "GET":
125                 response = webResource.accept(MEDIA_TYPE_JSON)
126                         .get(ClientResponse.class);
127                 break;
128             case "POST":
129                 response = webResource.accept(MEDIA_TYPE_JSON)
130                         .header("Content-Type", MEDIA_TYPE_JSON)
131                         .post(ClientResponse.class, expand(fJson));
132                 UuidHelper.setUuid(response.getEntity(String.class));
133                 saveUuid(fPath);
134                 break;
135             case "PUT":
136                 response = webResource.accept(MEDIA_TYPE_JSON)
137                         .header("Content-Type", MEDIA_TYPE_JSON)
138                         .put(ClientResponse.class, fJson);
139                 break;
140             case "DELETE":
141                 response = webResource.delete(ClientResponse.class);
142                 UuidHelper.setUuid("");
143                 break;
144             default:
145                 fail("Unsupported operation");
146         }
147         assertEquals(fExpectedStatusCode, response.getStatus());
148     }
149
150     private String expand(String content){
151         if (content.contains(NODE_ID_REPLACEMENT_PATTERN)) {
152             content = content.replace(NODE_ID_REPLACEMENT_PATTERN,
153                     node.getNodeIDString());
154         }
155         if (content.contains(UUID_REPLACEMENT_PATTERN)) {
156             content = content.replace(UUID_REPLACEMENT_PATTERN,
157                     UuidHelper.getUuid());
158         }
159         if (content.contains(BRIDGE_UUID_REPLACEMENT_PATTERN)) {
160             content = content.replace(BRIDGE_UUID_REPLACEMENT_PATTERN,
161                     UuidHelper.getBridgeUuid());
162         }
163         if (content.contains(PORT_UUID_REPLACEMENT_PATTERN)) {
164             content = content.replace(PORT_UUID_REPLACEMENT_PATTERN,
165                     UuidHelper.getPortUuid());
166         }
167         if (content.contains(QOS_UUID_REPLACEMENT_PATTERN)) {
168             content = content.replace(QOS_UUID_REPLACEMENT_PATTERN,
169                     UuidHelper.getQosUuid());
170         }
171         if (content.contains(OVS_UUID_REPLACEMENT_PATTERN)) {
172             content = content.replace(OVS_UUID_REPLACEMENT_PATTERN,
173                     getOvsUuid());
174         }
175         return content;
176     }
177
178     private void saveUuid(String path){
179         if (path.contains("bridge")) {
180             UuidHelper.setBridgeUuid(UuidHelper.getUuid());
181         }
182         if (path.contains("port")) {
183             UuidHelper.setPortUuid(UuidHelper.getUuid());
184         }
185         if (path.contains("qos")) {
186             UuidHelper.setQosUuid(UuidHelper.getUuid());
187         }
188     }
189
190     private String getOvsUuid() {
191         if (UuidHelper.getOvsUuid() == null) {
192             Client client = Client.create();
193             client.addFilter(new HTTPBasicAuthFilter(USERNAME, PASSWORD));
194             String uri = OvsdbNorthboundV2IT.BASE_URI + "/ovsdb/nb/v2/node/OVS/${node}/tables/open_vswitch/rows";
195             WebResource webResource = client.resource(expand(uri));
196             ClientResponse response = webResource.accept(MEDIA_TYPE_JSON)
197                     .get(ClientResponse.class);
198
199             assertEquals(200, response.getStatus());
200
201             String row = response.getEntity(String.class);
202             assertNotNull(row);
203
204             try {
205                 ObjectMapper objectMapper = new ObjectMapper();
206                 JsonNode rowsNode = objectMapper.readTree(row).get("rows");
207                 assertNotNull(rowsNode);
208                 // The first fieldName is the UUID
209                 String uuid = rowsNode.fieldNames().next();
210                 assertNotNull(uuid);
211                 UuidHelper.setOvsUuid(uuid);
212             } catch (IOException e) {
213                 fail("Cannot get the UUID for the Open_vSwitch table");
214             }
215         }
216
217         return UuidHelper.getOvsUuid();
218     }
219
220     @Before
221     public void areWeReady() throws InterruptedException {
222         assertNotNull(bc);
223         boolean debugit = false;
224         Bundle b[] = bc.getBundles();
225         for (Bundle element : b) {
226             int state = element.getState();
227             if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
228                 log.info("Bundle:" + element.getSymbolicName() + " state:"
229                         + stateToString(state));
230                 debugit = true;
231             }
232         }
233         if (debugit) {
234             log.debug("Do some debugging because some bundle is unresolved");
235         }
236
237         // Fail if true, if false we are good to go!
238         assertFalse(debugit);
239
240         ServiceReference r = bc.getServiceReference(IUserManager.class.getName());
241         if (r != null) {
242             this.userManager = (IUserManager) bc.getService(r);
243         }
244         // If UserManager is null, cannot login to run tests.
245         assertTrue(this.userManager != null);
246
247         try {
248             node = getCompatPluginTestConnection();
249         } catch (Exception e) {
250             fail("Exception : "+e.getMessage());
251         }
252
253         // Wait before making a REST call to avoid overloading Tomcat
254         Thread.sleep(500);
255
256     }
257
258     @Configuration
259     public static Option[] configuration() {
260         return options(
261                 //
262                 systemProperty("logback.configurationFile").value(
263                         PathUtils.getBaseDir() + "/src/test/resources/logback.xml"
264                 ),
265
266                 systemProperty("org.eclipse.gemini.web.tomcat.config.path").value(
267                         PathUtils.getBaseDir() + "/src/test/resources/tomcat-server.xml"),
268
269                 // To start OSGi console for inspection remotely
270                 systemProperty("osgi.console").value("2401"),
271
272                 propagateSystemProperty("ovsdbserver.ipaddress"),
273                 propagateSystemProperty("ovsdbserver.port"),
274
275                 ConfigurationBundles.mdsalBundles(),
276                 ConfigurationBundles.controllerBundles(),
277                 ConfigurationBundles.controllerNorthboundBundles(),
278                 ConfigurationBundles.ovsdbLibraryBundles(),
279                 ConfigurationBundles.ovsdbDefaultSchemaBundles(),
280                 ConfigurationBundles.ovsdbPluginBundles(),
281                 mavenBundle("org.opendaylight.ovsdb", "northbound").versionAsInProject()
282         );
283     }
284 }