77ac8f1e1b854b026b93ce80015457cb9e475983
[policy/pap.git] / main / src / test / java / org / onap / policy / pap / main / rest / TestPapRestServer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  *  Modifications Copyright (C) 2019 AT&T Intellectual Property.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pap.main.rest;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
27
28 import java.io.IOException;
29 import java.lang.reflect.Constructor;
30 import java.lang.reflect.Modifier;
31 import java.security.SecureRandom;
32 import java.security.cert.X509Certificate;
33 import java.util.Properties;
34
35 import javax.net.ssl.SSLContext;
36 import javax.net.ssl.TrustManager;
37 import javax.net.ssl.X509TrustManager;
38 import javax.ws.rs.client.Client;
39 import javax.ws.rs.client.ClientBuilder;
40 import javax.ws.rs.client.Invocation;
41 import javax.ws.rs.client.WebTarget;
42 import javax.ws.rs.core.MediaType;
43
44 import org.glassfish.jersey.client.ClientConfig;
45 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
46 import org.junit.After;
47 import org.junit.Test;
48 import org.onap.policy.common.endpoints.report.HealthCheckReport;
49 import org.onap.policy.common.utils.network.NetworkUtil;
50 import org.onap.policy.pap.main.PolicyPapException;
51 import org.onap.policy.pap.main.parameters.CommonTestData;
52 import org.onap.policy.pap.main.parameters.RestServerParameters;
53 import org.onap.policy.pap.main.startstop.Main;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 /**
58  * Class to perform unit test of {@link PapRestServer}.
59  *
60  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
61  */
62 public class TestPapRestServer {
63
64     private static final Logger LOGGER = LoggerFactory.getLogger(TestPapRestServer.class);
65     private static final String NOT_ALIVE = "not alive";
66     private static final String ALIVE = "alive";
67     private static final String SELF = "self";
68     private static final String NAME = "Policy PAP";
69     private static final String HEALTHCHECK_ENDPOINT = "healthcheck";
70     private static final String STATISTICS_ENDPOINT = "statistics";
71     private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
72     private Main main;
73     private PapRestServer restServer;
74
75     /**
76      * Method for cleanup after each test.
77      */
78     @After
79     public void teardown() {
80         PapStatisticsManager.getInstance().resetAllStatistics();
81
82         try {
83             if (NetworkUtil.isTcpPortOpen("localhost", 6969, 1, 1000L)) {
84                 if (main != null) {
85                     stopPapService(main);
86                 } else if (restServer != null) {
87                     restServer.stop();
88                 }
89             }
90         } catch (InterruptedException | IOException | PolicyPapException exp) {
91             LOGGER.error("teardown failed", exp);
92         }
93     }
94
95     @Test
96     public void testHealthCheckSuccess() {
97         try {
98             main = startPapService(true);
99             final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT);
100             final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
101             validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
102         } catch (final Exception exp) {
103             LOGGER.error("testHealthCheckSuccess failed", exp);
104             fail("Test should not throw an exception");
105         }
106     }
107
108     @Test
109     public void testHealthCheckFailure() throws Exception {
110         final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false);
111         restServerParams.setName(CommonTestData.PAP_GROUP_NAME);
112         restServer = new PapRestServer(restServerParams);
113         restServer.start();
114         final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT);
115         final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
116         validateHealthCheckReport(NAME, SELF, false, 500, NOT_ALIVE, report);
117         assertTrue(restServer.isAlive());
118         assertTrue(restServer.toString().startsWith("PapRestServer [servers="));
119     }
120
121     @Test
122     public void testHttpsHealthCheckSuccess() {
123         try {
124             main = startPapService(false);
125             final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT);
126             final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
127             validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
128         } catch (final Exception exp) {
129             LOGGER.error("testHttpsHealthCheckSuccess failed", exp);
130             fail("Test should not throw an exception");
131         }
132     }
133
134     @Test
135     public void testPapStatistics_200() {
136         try {
137             main = startPapService(true);
138             Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
139             StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
140             validateStatisticsReport(report, 0, 200);
141             updateDistributionStatistics();
142             invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
143             report = invocationBuilder.get(StatisticsReport.class);
144             validateStatisticsReport(report, 1, 200);
145         } catch (final Exception exp) {
146             LOGGER.error("testPapStatistics_200 failed", exp);
147             fail("Test should not throw an exception");
148         }
149     }
150
151     @Test
152     public void testPapStatistics_500() {
153         final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false);
154         restServerParams.setName(CommonTestData.PAP_GROUP_NAME);
155         restServer = new PapRestServer(restServerParams);
156         try {
157             restServer.start();
158             final Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
159             final StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
160             validateStatisticsReport(report, 0, 500);
161         } catch (final Exception exp) {
162             LOGGER.error("testPapStatistics_500 failed", exp);
163             fail("Test should not throw an exception");
164         }
165     }
166
167     @Test
168     public void testHttpsPapStatistic() {
169         try {
170             main = startPapService(false);
171             final Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT);
172             final StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
173             validateStatisticsReport(report, 0, 200);
174         } catch (final Exception exp) {
175             LOGGER.error("testHttpsDistributionStatistic failed", exp);
176             fail("Test should not throw an exception");
177         }
178     }
179
180     @Test
181     public void testPapStatisticsConstructorIsProtected() throws Exception {
182         final Constructor<PapStatisticsManager> constructor = PapStatisticsManager.class.getDeclaredConstructor();
183         assertTrue(Modifier.isProtected(constructor.getModifiers()));
184     }
185
186     private Main startPapService(final boolean http) {
187         final String[] papConfigParameters = new String[2];
188         if (http) {
189             papConfigParameters[0] = "-c";
190             papConfigParameters[1] = "parameters/PapConfigParameters.json";
191         } else {
192             final Properties systemProps = System.getProperties();
193             systemProps.put("javax.net.ssl.keyStore", KEYSTORE);
194             systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
195             System.setProperties(systemProps);
196             papConfigParameters[0] = "-c";
197             papConfigParameters[1] = "parameters/PapConfigParameters_Https.json";
198         }
199         return new Main(papConfigParameters);
200     }
201
202     private void stopPapService(final Main main) throws PolicyPapException {
203         main.shutdown();
204     }
205
206     private Invocation.Builder sendHttpRequest(final String endpoint) throws Exception {
207         final ClientConfig clientConfig = new ClientConfig();
208
209         final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
210         clientConfig.register(feature);
211
212         final Client client = ClientBuilder.newClient(clientConfig);
213         final WebTarget webTarget = client.target("http://localhost:6969/policy/pap/v1/" + endpoint);
214
215         final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
216
217         if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) {
218             throw new IllegalStateException("cannot connect to port 6969");
219         }
220         return invocationBuilder;
221     }
222
223     private Invocation.Builder sendHttpsRequest(final String endpoint) throws Exception {
224
225         final TrustManager[] noopTrustManager = new TrustManager[] { new X509TrustManager() {
226
227             @Override
228             public X509Certificate[] getAcceptedIssuers() {
229                 return new X509Certificate[0];
230             }
231
232             @Override
233             public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {}
234
235             @Override
236             public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {}
237         } };
238
239         final SSLContext sc = SSLContext.getInstance("TLSv1.2");
240         sc.init(null, noopTrustManager, new SecureRandom());
241         final ClientBuilder clientBuilder = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host,
242                 session) -> true);
243         final Client client = clientBuilder.build();
244         final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
245         client.register(feature);
246
247         final WebTarget webTarget = client.target("https://localhost:6969/policy/pap/v1/" + endpoint);
248
249         final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
250
251         if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) {
252             throw new IllegalStateException("cannot connect to port 6969");
253         }
254         return invocationBuilder;
255     }
256
257     private void updateDistributionStatistics() {
258         PapStatisticsManager mgr = PapStatisticsManager.getInstance();
259
260         mgr.updateTotalPdpCount();
261         mgr.updateTotalPdpGroupCount();
262         mgr.updateTotalPolicyDeployCount();
263         mgr.updatePolicyDeploySuccessCount();
264         mgr.updatePolicyDeployFailureCount();
265         mgr.updateTotalPolicyDownloadCount();
266         mgr.updatePolicyDownloadSuccessCount();
267         mgr.updatePolicyDownloadFailureCount();
268     }
269
270     private void validateStatisticsReport(final StatisticsReport report, final int count, final int code) {
271         assertEquals(code, report.getCode());
272         assertEquals(count, report.getTotalPdpCount());
273         assertEquals(count, report.getTotalPdpGroupCount());
274         assertEquals(count, report.getTotalPolicyDeployCount());
275         assertEquals(count, report.getPolicyDeploySuccessCount());
276         assertEquals(count, report.getPolicyDeployFailureCount());
277         assertEquals(count, report.getTotalPolicyDownloadCount());
278         assertEquals(count, report.getPolicyDeploySuccessCount());
279         assertEquals(count, report.getPolicyDeployFailureCount());
280     }
281
282     private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code,
283             final String message, final HealthCheckReport report) {
284         assertEquals(name, report.getName());
285         assertEquals(url, report.getUrl());
286         assertEquals(healthy, report.isHealthy());
287         assertEquals(code, report.getCode());
288         assertEquals(message, report.getMessage());
289     }
290 }