93a13049e0ca88ef0b66ca1526313404fd832c5c
[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
82 public class NetworkDiscoveryTest {
83     private static final String V1 = "v1";
84     private static final String APP = "junit";
85
86     private static final String RESOURCE_TYPE_VSERVER = "vserver";
87     private static final String CALLBACK_PATH = "/callback";
88
89     private static final String AUTH = "Basic " + Base64.getEncoder().encodeToString((
90             "admin:" + Password.deobfuscate("OBF:1u2a1toa1w8v1tok1u30")).getBytes());
91     @Autowired
92     private Environment environment;
93
94     @Rule
95     public WireMockRule enricherRule = new WireMockRule(wireMockConfig().port(9505));
96
97     @Rule
98     public WireMockRule callbackRule = new WireMockRule(wireMockConfig().dynamicPort());
99
100     @Autowired
101     private RestService service;
102
103     private String transactionId = UUID.randomUUID().toString();
104     private String requestId = UUID.randomUUID().toString();
105     private HttpServletRequest httpRequest = new TestHttpServletRequest();
106
107     public NetworkDiscoveryTest() throws URISyntaxException {
108
109     }
110
111     @Before
112     public void setUp() throws Exception {
113     }
114
115     @After
116     public void tearDown() throws Exception {
117     }
118
119     @Test
120     public void testNoAuthHeader() throws Exception {
121         // no Authorization header
122         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
123         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, null, APP, this.transactionId,
124                 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
125         assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
126         // should get WWW-Authenticate header in response
127         assertTrue(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE).startsWith("Basic realm"));
128     }
129
130     @Test
131     public void testUnauthorized() throws Exception {
132         String authorization = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());
133         // bad Authorization header
134         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
135         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, authorization, APP, this.transactionId,
136                 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
137         assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
138         // should not get WWW-Authenticate header in response
139         assertNull(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
140     }
141
142     @Test
143     public void testVerifyAppId() throws Exception {
144         // no X-FromAppId header
145         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
146         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, null, this.transactionId,
147                 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
148         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
149         assertTrue(((String)response.getEntity()).contains(ONAPLogConstants.Headers.PARTNER_NAME));
150     }
151
152     @Test
153     public void testVerifyRequestId() throws Exception {
154         // no X-FromAppId header
155         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
156         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
157                 null, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
158         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
159         assertTrue(((String)response.getEntity()).contains("requestId"));
160     }
161
162     @Test
163     public void testVerifyNotificationUrl() throws Exception {
164         // no X-FromAppId header
165         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
166         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
167                 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, null);
168         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
169         assertTrue(((String)response.getEntity()).contains("notificationURL"));
170     }
171
172     @Test
173     public void testVerifyResourceIds() throws Exception {
174         // no resourceIds list
175         {
176             List<String> resourceIds = null;
177             Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
178                     this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
179             assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
180             assertTrue(((String)response.getEntity()).contains("resourceIds"));
181         }
182
183         // empty resourceId list
184         {
185             List<String> resourceIds = new ArrayList<>();
186             Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
187                     this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
188             assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
189             assertTrue(((String)response.getEntity()).contains("resourceIds"));
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 }