c91d8adcbc3736dfffec6de3efec5e647108eede
[policy/api.git] / main / src / test / java / org / onap / policy / api / main / rest / provider / TestLegacyOperationalPolicyProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy API
4  * ================================================================================
5  * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019-2020 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.api.main.rest.provider;
25
26 import static org.assertj.core.api.Assertions.assertThatCode;
27 import static org.assertj.core.api.Assertions.assertThatThrownBy;
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertNotNull;
30 import static org.junit.Assert.assertTrue;
31 import static org.junit.Assert.fail;
32
33 import java.util.ArrayList;
34 import java.util.Base64;
35 import java.util.Collections;
36 import java.util.List;
37 import org.junit.After;
38 import org.junit.Before;
39 import org.junit.Test;
40 import org.onap.policy.api.main.parameters.ApiParameterGroup;
41 import org.onap.policy.common.parameters.ParameterService;
42 import org.onap.policy.common.utils.coder.StandardCoder;
43 import org.onap.policy.common.utils.coder.StandardYamlCoder;
44 import org.onap.policy.common.utils.resources.ResourceUtils;
45 import org.onap.policy.models.base.PfModelException;
46 import org.onap.policy.models.pdp.concepts.Pdp;
47 import org.onap.policy.models.pdp.concepts.PdpGroup;
48 import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
49 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
50 import org.onap.policy.models.pdp.enums.PdpHealthStatus;
51 import org.onap.policy.models.pdp.enums.PdpState;
52 import org.onap.policy.models.provider.PolicyModelsProvider;
53 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
54 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
56 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
57 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
58 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
59
60 /**
61  * This class performs unit test of {@link LegacyOperationalPolicyProvider}.
62  *
63  * @author Chenfei Gao (cgao@research.att.com)
64  */
65 public class TestLegacyOperationalPolicyProvider {
66
67     private static LegacyOperationalPolicyProvider operationalPolicyProvider;
68     private static PolicyTypeProvider policyTypeProvider;
69     private static PolicyModelsProviderParameters providerParams;
70     private static ApiParameterGroup apiParamGroup;
71     private static StandardCoder standardCoder;
72     private static StandardYamlCoder standardYamlCoder;
73
74     private static final String POLICY_RESOURCE = "policies/vCPE.policy.operational.legacy.input.json";
75     private static final String POLICY_RESOURCE_WITH_NO_VERSION =
76         "policies/vDNS.policy.operational.no.policyversion.json";
77     private static final String POLICY_TYPE_RESOURCE = "policytypes/onap.policies.controlloop.Operational.yaml";
78     private static final String POLICY_TYPE_ID = "onap.policies.controlloop.Operational:1.0.0";
79     private static final String POLICY_NAME = "operational.restart";
80     private static final String POLICY_VERSION = "1";
81     private static final String POLICY_TYPE_NAME = "onap.policies.controlloop.Operational";
82     private static final String POLICY_TYPE_VERSION = "1.0.0";
83     private static final String LEGACY_MINOR_PATCH_SUFFIX = ".0.0";
84
85     /**
86      * Initializes parameters.
87      *
88      * @throws PfModelException the PfModel parsing exception
89      */
90     @Before
91     public void setupParameters() throws PfModelException {
92
93         standardCoder = new StandardCoder();
94         standardYamlCoder = new StandardYamlCoder();
95         providerParams = new PolicyModelsProviderParameters();
96         providerParams.setDatabaseDriver("org.h2.Driver");
97         providerParams.setDatabaseUrl("jdbc:h2:mem:testdb");
98         providerParams.setDatabaseUser("policy");
99         providerParams.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
100         providerParams.setPersistenceUnit("ToscaConceptTest");
101         apiParamGroup =
102             new ApiParameterGroup("ApiGroup", null, providerParams, Collections.emptyList(), Collections.emptyList());
103         ParameterService.register(apiParamGroup, true);
104         operationalPolicyProvider = new LegacyOperationalPolicyProvider();
105         policyTypeProvider = new PolicyTypeProvider();
106     }
107
108     /**
109      * Closes up DB connections and deregisters API parameter group.
110      *
111      * @throws PfModelException the PfModel parsing exception
112      */
113     @After
114     public void tearDown() throws PfModelException {
115
116         operationalPolicyProvider.close();
117         policyTypeProvider.close();
118         ParameterService.deregister(apiParamGroup);
119     }
120
121     @Test
122     public void testFetchOperationalPolicy() throws Exception {
123
124         assertThatThrownBy(() -> {
125             operationalPolicyProvider.fetchOperationalPolicy("dummy", null);
126         }).hasMessage("service template not found in database");
127
128         assertThatThrownBy(() -> {
129             operationalPolicyProvider.fetchOperationalPolicy("dummy", "dummy");
130         }).hasMessageContaining("service template not found in database");
131
132         ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder
133             .decode(ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
134         policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
135
136         String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
137         LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
138         LegacyOperationalPolicy createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate);
139         assertNotNull(createdPolicy);
140
141         LegacyOperationalPolicy firstVersion =
142             operationalPolicyProvider.fetchOperationalPolicy("operational.restart", "1");
143         assertNotNull(firstVersion);
144         assertEquals("1", firstVersion.getPolicyVersion());
145
146         LegacyOperationalPolicy latestVersion =
147             operationalPolicyProvider.fetchOperationalPolicy("operational.restart", null);
148         assertNotNull(latestVersion);
149         assertEquals("1", latestVersion.getPolicyVersion());
150
151         assertThatThrownBy(() -> {
152             operationalPolicyProvider.fetchOperationalPolicy("operational.restart", "1.0.0");
153         }).hasMessageContaining("parameter \"version\": value \"1.0.0.0.0\", does not match regular expression");
154
155         assertThatThrownBy(() -> {
156             operationalPolicyProvider.fetchOperationalPolicy("operational.restart", "latest");
157             ;
158         }).hasMessageContaining("parameter \"version\": value \"latest.0.0\", does not match regular expression");
159
160         operationalPolicyProvider.deleteOperationalPolicy("operational.restart", "1");
161         policyTypeProvider.deletePolicyType("onap.policies.controlloop.Operational", "1.0.0");
162     }
163
164     @Test
165     public void testFetchDeployedOperationalPolicies() {
166
167         assertThatThrownBy(() -> {
168             operationalPolicyProvider.fetchDeployedOperationalPolicies("dummy");
169         }).hasMessage("could not find policy with ID dummy and type " + POLICY_TYPE_ID + " deployed in any pdp group");
170
171         try (PolicyModelsProvider databaseProvider =
172             new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParams)) {
173             assertEquals(0, databaseProvider.getPdpGroups("name").size());
174             assertEquals(0, databaseProvider.getFilteredPdpGroups(PdpGroupFilter.builder().build()).size());
175
176             assertNotNull(databaseProvider.createPdpGroups(new ArrayList<>()));
177             assertNotNull(databaseProvider.updatePdpGroups(new ArrayList<>()));
178
179             PdpGroup pdpGroup = new PdpGroup();
180             pdpGroup.setName("group");
181             pdpGroup.setVersion("1.2.3");
182             pdpGroup.setPdpGroupState(PdpState.ACTIVE);
183             pdpGroup.setPdpSubgroups(new ArrayList<>());
184             List<PdpGroup> groupList = new ArrayList<>();
185             groupList.add(pdpGroup);
186
187             PdpSubGroup pdpSubGroup = new PdpSubGroup();
188             pdpSubGroup.setPdpType("type");
189             pdpSubGroup.setDesiredInstanceCount(123);
190             pdpSubGroup.setSupportedPolicyTypes(new ArrayList<>());
191             pdpSubGroup.getSupportedPolicyTypes()
192                 .add(new ToscaPolicyTypeIdentifier(POLICY_TYPE_NAME, POLICY_TYPE_VERSION));
193             pdpGroup.getPdpSubgroups().add(pdpSubGroup);
194
195             Pdp pdp = new Pdp();
196             pdp.setInstanceId("type-0");
197             pdp.setMessage("Hello");
198             pdp.setPdpState(PdpState.ACTIVE);
199             pdp.setHealthy(PdpHealthStatus.UNKNOWN);
200             pdpSubGroup.setPdpInstances(new ArrayList<>());
201             pdpSubGroup.getPdpInstances().add(pdp);
202
203             // Create Pdp Groups
204             assertEquals(123,
205                 databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0).getDesiredInstanceCount());
206             assertEquals(1, databaseProvider.getPdpGroups("group").size());
207
208             // Create Policy Type
209             assertThatCode(() -> {
210                 ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder
211                     .decode(ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
212                 policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
213             }).doesNotThrowAnyException();
214
215             // Create Policy
216             assertThatCode(() -> {
217                 String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
218                 LegacyOperationalPolicy policyToCreate =
219                     standardCoder.decode(policyString, LegacyOperationalPolicy.class);
220                 LegacyOperationalPolicy policyCreated =
221                     operationalPolicyProvider.createOperationalPolicy(policyToCreate);
222                 assertEquals("operational.restart", policyCreated.getPolicyId());
223                 assertEquals("1", policyCreated.getPolicyVersion());
224                 assertNotNull(policyCreated.getContent());
225             }).doesNotThrowAnyException();
226
227             // Test fetchDeployedPolicies (deployedPolicyMap.isEmpty())==true
228             assertThatThrownBy(() -> {
229                 operationalPolicyProvider.fetchDeployedOperationalPolicies(POLICY_NAME);
230             }).hasMessage("could not find policy with ID " + POLICY_NAME + " and type " + POLICY_TYPE_ID
231                 + " deployed in any pdp group");
232
233             // Update pdpSubGroup
234             pdpSubGroup.setPolicies(new ArrayList<>());
235             pdpSubGroup.getPolicies()
236                 .add(new ToscaPolicyIdentifier(POLICY_NAME, POLICY_VERSION + LEGACY_MINOR_PATCH_SUFFIX));
237             assertEquals(1,
238                 databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0).getPolicies().size());
239
240             // Test fetchDeployedPolicies
241             assertThatCode(() -> {
242                 operationalPolicyProvider.fetchDeployedOperationalPolicies(POLICY_NAME);
243             }).doesNotThrowAnyException();
244
245             // Test validateDeleteEligibility exception path(!pdpGroups.isEmpty())
246             assertThatThrownBy(() -> {
247                 operationalPolicyProvider.deleteOperationalPolicy(POLICY_NAME, POLICY_VERSION);
248             }).hasMessageContaining("policy is in use, it is deployed in PDP group group subgroup type");
249         } catch (Exception exc) {
250             fail("Test should not throw an exception");
251         }
252     }
253
254     @Test
255     public void testCreateOperationalPolicy() throws Exception {
256
257         assertThatThrownBy(() -> {
258             String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
259             LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
260             operationalPolicyProvider.createOperationalPolicy(policyToCreate);
261         }).hasMessageContaining(
262             "no policy types are defined on the service template for the policies in the topology template");
263
264         ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder
265             .decode(ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
266         policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
267
268         String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
269         LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
270         LegacyOperationalPolicy createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate);
271         assertNotNull(createdPolicy);
272         assertEquals("operational.restart", createdPolicy.getPolicyId());
273         assertTrue(createdPolicy.getContent().startsWith("controlLoop%3A%0A%20%20version%3A%202.0.0%0A%20%20"));
274
275         String defaultPolicyVersionString = ResourceUtils.getResourceAsString(POLICY_RESOURCE_WITH_NO_VERSION);
276         LegacyOperationalPolicy defaultPolicyVersionPolicy =
277             standardCoder.decode(defaultPolicyVersionString, LegacyOperationalPolicy.class);
278         createdPolicy = operationalPolicyProvider.createOperationalPolicy(defaultPolicyVersionPolicy);
279         assertEquals("1", createdPolicy.getPolicyVersion());
280
281         assertThatCode(() -> {
282             String duplicatePolicyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
283             LegacyOperationalPolicy duplicatePolicyToCreate =
284                 standardCoder.decode(duplicatePolicyString, LegacyOperationalPolicy.class);
285             operationalPolicyProvider.createOperationalPolicy(duplicatePolicyToCreate);
286         }).doesNotThrowAnyException();
287
288         assertThatThrownBy(() -> {
289             String duplicatePolicyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
290             LegacyOperationalPolicy duplicatePolicyToCreate =
291                 standardCoder.decode(duplicatePolicyString, LegacyOperationalPolicy.class);
292             duplicatePolicyToCreate.setContent("some other content");
293             operationalPolicyProvider.createOperationalPolicy(duplicatePolicyToCreate);
294         }).hasMessageContaining("INVALID:entity in incoming fragment does not equal existing entity");
295     }
296
297     @Test
298     public void testDeleteOperationalPolicyException() {
299         String policyId = "operational.restart";
300         String policyVersion = "1";
301         String policyTypeVersion = "1.0.0";
302         String policyTypeId = "onap.policies.controlloop.Operational";
303         String legacyMinorPatchSuffix = ".0.0";
304
305         try (PolicyModelsProvider databaseProvider =
306             new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParams)) {
307             assertEquals(0, databaseProvider.getPdpGroups("name").size());
308             assertEquals(0, databaseProvider.getFilteredPdpGroups(PdpGroupFilter.builder().build()).size());
309
310             assertNotNull(databaseProvider.createPdpGroups(new ArrayList<>()));
311             assertNotNull(databaseProvider.updatePdpGroups(new ArrayList<>()));
312
313             PdpGroup pdpGroup = new PdpGroup();
314             pdpGroup.setName("group");
315             pdpGroup.setVersion("1.2.3");
316             pdpGroup.setPdpGroupState(PdpState.ACTIVE);
317             pdpGroup.setPdpSubgroups(new ArrayList<>());
318             List<PdpGroup> groupList = new ArrayList<>();
319             groupList.add(pdpGroup);
320
321             PdpSubGroup pdpSubGroup = new PdpSubGroup();
322             pdpSubGroup.setPdpType("type");
323             pdpSubGroup.setDesiredInstanceCount(123);
324             pdpSubGroup.setSupportedPolicyTypes(new ArrayList<>());
325             pdpSubGroup.getSupportedPolicyTypes().add(new ToscaPolicyTypeIdentifier(policyTypeId, policyTypeVersion));
326             pdpGroup.getPdpSubgroups().add(pdpSubGroup);
327
328             Pdp pdp = new Pdp();
329             pdp.setInstanceId("type-0");
330             pdp.setMessage("Hello");
331             pdp.setPdpState(PdpState.ACTIVE);
332             pdp.setHealthy(PdpHealthStatus.UNKNOWN);
333             pdpSubGroup.setPdpInstances(new ArrayList<>());
334             pdpSubGroup.getPdpInstances().add(pdp);
335
336             // Create Pdp Groups
337             assertEquals(123,
338                 databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0).getDesiredInstanceCount());
339             assertEquals(1, databaseProvider.getPdpGroups("group").size());
340
341             // Create Policy Type
342             assertThatCode(() -> {
343                 ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder
344                     .decode(ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
345                 policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
346             }).doesNotThrowAnyException();
347
348             // Create Policy
349             assertThatCode(() -> {
350                 String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
351                 LegacyOperationalPolicy policyToCreate =
352                     standardCoder.decode(policyString, LegacyOperationalPolicy.class);
353                 LegacyOperationalPolicy createdPolicy =
354                     operationalPolicyProvider.createOperationalPolicy(policyToCreate);
355                 assertNotNull(createdPolicy);
356             }).doesNotThrowAnyException();
357
358             // Update pdpSubGroup
359             pdpSubGroup.setPolicies(new ArrayList<>());
360             pdpSubGroup.getPolicies().add(new ToscaPolicyIdentifier(policyId, policyVersion + legacyMinorPatchSuffix));
361             assertEquals(1,
362                 databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0).getPolicies().size());
363             assertThatThrownBy(() -> {
364                 operationalPolicyProvider.deleteOperationalPolicy(policyId, policyVersion);
365             }).hasMessageContaining("policy is in use, it is deployed in PDP group group subgroup type");
366         } catch (Exception exc) {
367             fail("Test should not throw an exception");
368         }
369     }
370
371     @Test
372     public void testDeleteOperationalPolicy() {
373
374         assertThatThrownBy(() -> {
375             operationalPolicyProvider.deleteOperationalPolicy("dummy", null);
376         }).hasMessageMatching("^policyVersion is marked .*on.*ull but is null$");
377
378         assertThatThrownBy(() -> {
379             operationalPolicyProvider.deleteOperationalPolicy("dummy", "dummy");
380         }).hasMessageContaining("parameter \"version\": value \"dummy.0.0\", does not match regular expression");
381
382         assertThatCode(() -> {
383             ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder
384                 .decode(ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
385             policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
386
387             String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
388             LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
389             LegacyOperationalPolicy createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate);
390             assertNotNull(createdPolicy);
391
392             LegacyOperationalPolicy deletedPolicy =
393                 operationalPolicyProvider.deleteOperationalPolicy("operational.restart", "1");
394             assertNotNull(deletedPolicy);
395             assertEquals("operational.restart", deletedPolicy.getPolicyId());
396             assertTrue(deletedPolicy.getContent().startsWith("controlLoop%3A%0A%20%20version%3A%202.0.0%0A%20%20"));
397         }).doesNotThrowAnyException();
398
399         assertThatThrownBy(() -> {
400             operationalPolicyProvider.deleteOperationalPolicy("operational.restart", "1");
401         }).hasMessage("no policies found");
402
403         assertThatCode(() -> {
404             policyTypeProvider.deletePolicyType("onap.policies.controlloop.Operational", "1.0.0");
405         }).doesNotThrowAnyException();
406     }
407 }