100c6717f5911b6ef777838a2ee14e40804136cc
[sdnc/apps.git] /
1 /*
2  *  ============LICENSE_START===================================================
3  * Copyright (c) 2018 Amdocs
4  * ============================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ============LICENSE_END=====================================================
17  */
18
19 package org.onap.sdnc.apps.pomba.networkdiscovery.unittest.service;
20
21 import static com.github.tomakehurst.wiremock.client.WireMock.get;
22 import static com.github.tomakehurst.wiremock.client.WireMock.ok;
23 import static com.github.tomakehurst.wiremock.client.WireMock.okTextXml;
24 import static com.github.tomakehurst.wiremock.client.WireMock.post;
25 import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertNull;
28 import static org.junit.Assert.assertTrue;
29 import static org.junit.Assert.fail;
30
31 import com.fasterxml.jackson.databind.AnnotationIntrospector;
32 import com.fasterxml.jackson.databind.ObjectMapper;
33 import com.fasterxml.jackson.databind.type.TypeFactory;
34 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
35 import com.github.tomakehurst.wiremock.junit.WireMockRule;
36 import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
37 import com.github.tomakehurst.wiremock.verification.LoggedRequest;
38 import java.net.URISyntaxException;
39 import java.text.MessageFormat;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Base64;
43 import java.util.List;
44 import java.util.UUID;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.ws.rs.core.HttpHeaders;
47 import javax.ws.rs.core.Response;
48 import javax.ws.rs.core.Response.Status;
49 import org.eclipse.jetty.util.security.Password;
50 import org.junit.After;
51 import org.junit.Before;
52 import org.junit.Rule;
53 import org.junit.Test;
54 import org.junit.runner.RunWith;
55 import org.onap.logging.ref.slf4j.ONAPLogConstants;
56 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.Attribute;
57 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.DataQuality;
58 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryNotification;
59 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryResponse;
60 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.Resource;
61 import org.onap.sdnc.apps.pomba.networkdiscovery.service.rs.RestService;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
64 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
65 import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
66 import org.springframework.boot.test.context.SpringBootTest;
67 import org.springframework.core.env.Environment;
68 import org.springframework.test.context.TestPropertySource;
69 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
70 import org.springframework.test.context.web.WebAppConfiguration;
71
72 @RunWith(SpringJUnit4ClassRunner.class)
73 @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
74 @WebAppConfiguration
75 @SpringBootTest
76 @TestPropertySource(properties = {
77         "enricher.url=http://localhost:9505",
78         "basicAuth.username=admin",
79         "basicAuth.password=OBF:1u2a1toa1w8v1tok1u30"
80 })
81 public class NetworkDiscoveryTest {
82     private static final String V1 = "v1";
83     private static final String APP = "junit";
84
85     private static final String RESOURCE_TYPE_VSERVER = "vserver";
86     private static final String CALLBACK_PATH = "/callback";
87
88     private static final String AUTH = "Basic " + Base64.getEncoder().encodeToString((
89             "admin:" + Password.deobfuscate("OBF:1u2a1toa1w8v1tok1u30")).getBytes());
90     @Autowired
91     private Environment environment;
92
93     @Rule
94     public WireMockRule enricherRule = new WireMockRule(wireMockConfig().port(9505));
95
96     @Rule
97     public WireMockRule callbackRule = new WireMockRule(wireMockConfig().dynamicPort());
98
99     @Autowired
100     private RestService service;
101
102     private String transactionId = UUID.randomUUID().toString();
103     private String requestId = UUID.randomUUID().toString();
104     private HttpServletRequest httpRequest = new TestHttpServletRequest();
105
106     public NetworkDiscoveryTest() throws URISyntaxException {
107
108     }
109
110     @Before
111     public void setUp() throws Exception {
112     }
113
114     @After
115     public void tearDown() throws Exception {
116     }
117
118     @Test
119     public void testNoAuthHeader() throws Exception {
120         // no Authorization header
121         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
122         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, null, APP, this.transactionId,
123                 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
124         assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
125         // should get WWW-Authenticate header in response
126         assertTrue(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE).startsWith("Basic realm"));
127     }
128
129     @Test
130     public void testUnauthorized() throws Exception {
131         String authorization = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());
132         // bad Authorization header
133         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
134         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, authorization, APP, this.transactionId,
135                 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
136         assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
137         // should not get WWW-Authenticate header in response
138         assertNull(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
139     }
140
141     @Test
142     public void testVerifyAppId() throws Exception {
143         // no X-FromAppId header
144         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
145         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, null, this.transactionId,
146                 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
147         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
148         assertTrue(((String)response.getEntity()).contains(ONAPLogConstants.Headers.PARTNER_NAME));
149     }
150
151     @Test
152     public void testVerifyRequestId() throws Exception {
153         // no X-FromAppId header
154         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
155         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
156                 null, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
157         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
158         assertTrue(((String)response.getEntity()).contains("requestId"));
159     }
160
161     @Test
162     public void testVerifyNotificationUrl() throws Exception {
163         // no X-FromAppId header
164         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
165         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
166                 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, null);
167         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
168         assertTrue(((String)response.getEntity()).contains("notificationURL"));
169     }
170
171     @Test
172     public void testVerifyResourceIds() throws Exception {
173         // no resourceIds list
174         {
175             List<String> resourceIds = null;
176             Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
177                     this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
178             assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
179             assertTrue(((String)response.getEntity()).contains("resourceIds"));
180         }
181
182         // empty resourceId list
183         {
184             List<String> resourceIds = new ArrayList<>();
185             Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
186                     this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
187             assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
188             assertTrue(((String)response.getEntity()).contains("resourceIds"));
189         }
190     }
191
192
193     @Test
194     public void testVerifyResourceType() throws Exception {
195         // no resource type
196         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
197         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
198                 this.requestId, null, resourceIds, getCallbackUrl());
199         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
200         assertTrue(((String)response.getEntity()).contains("resourceType"));
201     }
202
203     @Test
204     public void testDiscoverVserver() throws Exception {
205         String vserverId = UUID.randomUUID().toString();
206
207         String resourcePath = MessageFormat.format(
208                 this.environment.getProperty("enricher.type.vserver.url"),
209                 new Object[] { vserverId });
210
211         String enricherPayload = String.format(
212                 "<vserver xmlns=\"http://org.onap.aai.inventory/v11\">\r\n"
213                 + "   <vserver-id>%s</vserver-id>\r\n"
214                 + "   <power-state>1</power-state>\r\n"
215                 + "   <vm-state>active</vm-state>\r\n"
216                 + "   <status>ACTIVE</status>\r\n"
217                 + "   <host-status>UNKNOWN</host-status>\r\n"
218                 + "   <updated>2017-11-20T04:26:13Z</updated>\r\n"
219                 + "   <disk-allocation-gb>.010</disk-allocation-gb>\r\n"
220                 + "   <memory-usage-mb>null</memory-usage-mb>\r\n"
221                 + "   <cpu-util-percent>.043</cpu-util-percent>\r\n"
222                 + "   <retrieval-timestamp>2018-06-27 19:41:49 +0000</retrieval-timestamp>\r\n"
223                 + "</vserver>", vserverId);
224
225         this.enricherRule.stubFor(get(resourcePath).willReturn(okTextXml(enricherPayload)));
226
227         this.callbackRule.stubFor(post(CALLBACK_PATH).willReturn(ok("Acknowledged")));
228
229         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
230                 RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId), getCallbackUrl());
231
232         assertEquals(Status.OK.getStatusCode(), response.getStatus());
233         NetworkDiscoveryResponse entity = (NetworkDiscoveryResponse) response.getEntity();
234         assertEquals(requestId, entity.getRequestId());
235         assertEquals(Status.ACCEPTED.getStatusCode(), entity.getCode().intValue());
236         assertEquals(Boolean.FALSE, entity.getAckFinalIndicator());
237
238         List<ServeEvent> events = waitForRequests(this.callbackRule, 1, 10);
239         LoggedRequest notificationRequest = events.get(0).getRequest();
240         assertEquals(AUTH, notificationRequest.getHeader(HttpHeaders.AUTHORIZATION));
241         String notificationJson = notificationRequest.getBodyAsString();
242
243         ObjectMapper mapper = new ObjectMapper();
244         AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
245         mapper.setAnnotationIntrospector(introspector);
246         NetworkDiscoveryNotification notification =
247                 mapper.readValue(notificationJson, NetworkDiscoveryNotification.class);
248
249         assertEquals(requestId, notification.getRequestId());
250         assertEquals(Status.OK.getStatusCode(), notification.getCode().intValue());
251         assertEquals(Boolean.TRUE, notification.getAckFinalIndicator());
252
253         assertEquals(1, notification.getResources().size());
254         Resource vserver = notification.getResources().get(0);
255         assertEquals(vserverId, vserver.getId());
256         assertEquals("vserver", vserver.getType());
257         assertEquals(DataQuality.Status.ok, vserver.getDataQuality().getStatus());
258
259         verifyAttribute(vserver.getAttributeList(), "power-state", "1");
260         verifyAttribute(vserver.getAttributeList(), "vm-state", "active");
261         verifyAttribute(vserver.getAttributeList(), "status", "ACTIVE");
262         verifyAttribute(vserver.getAttributeList(), "host-status", "UNKNOWN");
263         verifyAttribute(vserver.getAttributeList(), "updated", "2017-11-20T04:26:13Z");
264         verifyAttribute(vserver.getAttributeList(), "disk-allocation-gb", ".010");
265         verifyAttribute(vserver.getAttributeList(), "memory-usage-mb", "null");
266         verifyAttribute(vserver.getAttributeList(), "cpu-util-percent", ".043");
267         verifyAttribute(vserver.getAttributeList(), "retrieval-timestamp", "2018-06-27 19:41:49 +0000");
268     }
269
270     /**
271      * Verify API returns a final response indicating no discovery possible.
272      */
273     @Test
274     public void testUnsupportedResourceType() throws Exception {
275
276         String resourceType = "unsupported";
277         List<String> resourceIds = Arrays.asList("dummyId");
278         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
279                 this.requestId, resourceType, resourceIds, getCallbackUrl());
280         assertEquals(Status.OK.getStatusCode(), response.getStatus());
281
282         NetworkDiscoveryResponse entity = (NetworkDiscoveryResponse) response.getEntity();
283         assertEquals(Boolean.TRUE, entity.getAckFinalIndicator());
284         assertEquals(Status.NO_CONTENT.getStatusCode(), entity.getCode().intValue());
285     }
286
287     private void verifyAttribute(List<Attribute> attributeList, String attrName, String attrValue) {
288         for (Attribute attr : attributeList) {
289             if (attr.getName().equals(attrName)) {
290                 assertEquals("Unexpected value for attribute " + attrName, attrValue, attr.getValue());
291                 return;
292             }
293         }
294         fail("Attribute " + attrName + " not found");
295     }
296
297     private List<ServeEvent> waitForRequests(WireMockRule service, int minRequests, long timeoutSeconds)
298             throws InterruptedException {
299
300         long remaining = timeoutSeconds * 1000L;
301         long retryInterval = Math.min(remaining / 5, 1000);
302         while (true) {
303             List<ServeEvent> events = service.getAllServeEvents();
304             if (events.size() >= minRequests) {
305                 return events;
306             }
307             if (remaining <= 0) {
308                 fail("Timeout waiting for " + minRequests + " requests");
309             }
310             Thread.sleep(retryInterval);
311             remaining -= retryInterval;
312         }
313     }
314
315     private String getCallbackUrl() {
316         return "http://localhost:" + this.callbackRule.port() + CALLBACK_PATH;
317     }
318 }